当我创建我的ApplicationContext
时myBean 构造函数已成功使用。
但创建后,bean 是 null
使用@Autowired
标签。
我虽然@Autowired
将取代getBean()
不知何故?我是不是理解错了?
当我已经创建了 Bean(在 ApplicationContext 启动期间)并 Autowiring 它们时,为什么还需要调用 GetBean?
这是我到目前为止所做的:
主要:
@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)
}
任何其他类:
public class AnyOtherClass {
@Autowired
protected SomeBean someBean;
public AnyOtherClass(){
someBean.doSomething();//Nullpointer
}
应用程序配置:
@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..");
}
}
注意:接口(interface)ApplicationContextAware
工作正常,但没有 @Autowired
。我真的很想选择 @Autowired
因为它对我来说听起来更舒服并且更不容易出错。
最佳答案
要使 @Autowired
在 AnyOtherClass
中工作,AnyOtherClass
必须是 Spring bean。
像这样的事情
AppConfig
@Configuration
public class AppConfig {
@Bean
@Autowired
public SomeBean BeanSomeBean() {
return new SomeBean();
}
@Bean
@Autowired
public AnyOtherClass BeanAnyOtherClass() {
return new AnyOtherClass();
}
}
主要
@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 = ctx.getBean(AnyOtherClass.class);
}
如果您使用new AnyOtherClass()
实例化一个类,它将绕过Spring并且所有注释都不起作用。您必须将其从 Spring 上下文中取出才能使其成为 Spring bean。
关于java - 创建ApplicationContext后@Autowired Spring NullPointerException Null Beans,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27379216/