首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >spring boot中的原语类型依赖项注入

spring boot中的原语类型依赖项注入
EN

Stack Overflow用户
提问于 2018-01-11 22:00:49
回答 1查看 685关注 0票数 1

你能给我提供一个spring boot中的原始类型依赖注入的例子吗?我已经尝试过一次,但是我的自定义bean定义类TestConfiguration不能检测到spring boot应用程序,或者不能识别它。这是我的代码,

//Engine类

代码语言:javascript
复制
package com.test2.projectTest;

import org.springframework.stereotype.Component;

@Component
public class Engine {

private String msg;

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}
}

//测试配置

代码语言:javascript
复制
package com.test2.projectTest;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TestConfiguration {

@Bean("engine")
public Engine engine(){
    Engine engine = new Engine();
    engine.setMsg("Message is injected");
    return engine;
}
}

//spring主应用

代码语言:javascript
复制
package com.test2.projectTest;

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class ProjectTestApplication {

public static void main(String[] args) {
    SpringApplication.run(ProjectTestApplication.class, args);
}
}

//JUnit测试

代码语言:javascript
复制
package com.test2.projectTest;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.ApplicationContext;
import 
org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ProjectTestApplicationTests {

@Test
public void contextLoads() {

    ApplicationContext apc = new 
AnnotationConfigApplicationContext(TestConfiguration.class);
    Engine e = (Engine) apc.getBean("engine");
    e.getMsg();
}
}

// Output - org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No bean named 'engine' available

请对上述问题提出任何解决方案

EN

回答 1

Stack Overflow用户

发布于 2018-01-12 01:06:44

在主类中添加@componentscan注释,并提供引擎类包即可工作

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48208828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档