創建我的ApplicationContext
時,myBean構造函數已成功使用。 但創建豆後,使用@Autowired
標籤的null
。@Autowired Spring NullPointerException ApplicationContext創建後的空Bean
我雖然@Autowired
會以某種方式取代getBean()
?我得到這個錯誤?
爲什麼我需要調用GetBean,當我已經創建了我的Beans(在ApplicationContext啓動過程中)並且還自動裝配它們?
這是我迄今所做的:
主營:
@EnableAutoConfiguration
@Configuration
@ComponentScan("com.somePackage")
public class Main {
ApplicationContext ctx= new AnnotationConfigApplicationContext(AppConfig.class);
SomeBean myBean = ctx.getBean(SomeBean.class);
myBean.doSomething();//succeeds
AnyOtherClass aoc = new AnyOtherClass();//Nullpointer (see AnyOtherClass.class for details)
}
AnyOtherClass:
public class AnyOtherClass {
@Autowired
protected SomeBean someBean;
public AnyOtherClass(){
someBean.doSomething();//Nullpointer
}
的AppConfig:
@Configuration
public class AppConfig {
@Bean
@Autowired
public SomeBean BeanSomeBean() {
return new SomeBean();
}
}
爲myBean:
public class SomeBean {
public SomeBean(){}
public void doSomething() {
System.out.println("do Something..");
}
}
注:接口ApplicationContextAware
工作正常,但沒有@Autowired
。我真的很想和@Autowired
一起去,因爲它聽起來更舒服,對我來說更不容易。
使'AnyOtherClass'具有'@ Component'註釋並確保自動掃描看到它 – EpicPandaForce 2014-12-09 12:47:13