@Autowired 在 spring 引导 Web 项目中失败
@Autowired fails in spring boot web project
我有一个简单的 Spring 引导 Web 项目,直接来自模板:
@SpringBootApplication
@RestController
public class HelloWorldRestApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldRestApplication.class, args);
Performer p = new Performer();
p.perform();
}
}
我有一个确保自动装配工作的测试,事实上它在这个测试中确实如此 class(示例来自 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) 没有帮助。
我错过了什么?
尝试在主 class 中启用 @ComponentScan
包并从 ApplicationContext
获取 Performer
class 实例,如下所示:
@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();
}
}
我有一个简单的 Spring 引导 Web 项目,直接来自模板:
@SpringBootApplication
@RestController
public class HelloWorldRestApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldRestApplication.class, args);
Performer p = new Performer();
p.perform();
}
}
我有一个确保自动装配工作的测试,事实上它在这个测试中确实如此 class(示例来自 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) 没有帮助。
我错过了什么?
尝试在主 class 中启用 @ComponentScan
包并从 ApplicationContext
获取 Performer
class 实例,如下所示:
@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();
}
}