当我创建ApplicationContext
时,成功使用了myBean构造函数。
但是在创建之后,bean使用null
标记为@Autowired
。
我虽然@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
一起去,因为它听起来更舒服,对我来说也不那么错误。
答案 0 :(得分:2)
要让@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。
答案 1 :(得分:0)
尝试
@Component
public class AnyOtherClass {
@Autowired
protected SomeBean someBean;
public AnyOtherClass(){
someBean.doSomething();//Nullpointer
}
此外,您需要确保此类位于com.somePackage包中。