@Autowired在spring boot web项目中失败

时间:2015-08-19 10:39:26

标签: java spring spring-boot autowired

我有一个简单的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)并没有帮助。

我想念什么?

1 个答案:

答案 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();
    }
}