我有一个简单的Spring Boot Web项目,就在模板中:
@SpringBootApplication
@RestController
public class HelloWorldRestApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldRestApplication.class, args);
Performer p = new Performer();
p.perform();
}
}
我有一个测试来确保自动装配工作,事实上它确实在这个测试类中(示例来自Spring in Action,4th):
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest {
@Autowired
private CDPlayer cdp;
@Test
public void cdShouldNotBeNull(){
assertNotNull(cdp);
}
}
和
public class Performer {
@Autowired
private CDPlayer cdp;
public void perform(){
System.out.println(cdp);
cdp.play();
}
public CDPlayer getCdp() {
return cdp;
}
public void setCdp(CDPlayer cdp) {
this.cdp = cdp;
}
}
和
@Component
public class CDPlayer{
public void play(){
System.out.println("play");
}
}
配置:
@Configuration
@ComponentScan
public class CDPlayerConfig {
}
但是,它在HelloWorldRestApplication中不起作用,我得到null。
添加@ContextConfiguration(classes = CDPlayerConfig.class)并没有帮助。
我想念什么?
答案 0 :(得分:0)
尝试在您的主课程中启用@ComponentScan
您的软件包,并从Performer
获取ApplicationContext
类实例,如下所示:
@SpringBootApplication
@RestController
@ComponentScan({“package.name.1”,”package.name.2”})
public class HelloWorldRestApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(HelloWorldRestApplication.class, args);
Performer p = ctx.getBean(Performer.class);//get the bean by type
p.perform();
}
}