我有一个像这样的例子
班级Other
需要MyBean
的实例,因此我创建了一个属性,并在创建时使用该属性并Other
@Configuration
public SomeClass {
@Resource
private MyBean b;
@Autowired
Environment env;
@Bean
public MyBean myBean() {
MyBean b = new MyBean();
b.foo(env.getProperty("mb"); // NPE
return b;
}
@Bean
public Other other() {
Other o = new Other(o);
return o;
}
}
但是我在初始化NullPointerException
对象时得到myBean
,我想这是因为env
属性在那时还没有连线。
如果我不使用bean并直接使用该方法,一切都运行良好。
@Configuration
public SomeClass {
@Autowired
Environment env;
@Bean
public MyBean myBean() {
MyBean b = new MyBean();
b.foo(env.getProperty("mb"); // NPE
return b;
}
@Bean
public Other other() {
Other o = new Other(myBean());
return o;
}
}
是因为我在同一个@Bean
课程中定义了@Configuration
吗?
答案 0 :(得分:1)
尽管它作为一个概念性问题很有意思,但Spring Java配置的使用方法只是将所需的bean作为参数传递,因此您可以避免将bean自动装配为配置类的字段。如果您的任何bean碰巧需要MyBean
实例,只需将其作为参数提供:
@Bean
public Other other(MyBean myBean) {
Other o = new Other(myBean);
return o;
}
从您的配置类调用@Bean
anotated方法也没有问题,就像您在第二个代码段中所做的那样,因为它们是proxied and cached,因此它们不会创建不必要的实例。但是,我倾向于遵循上面的代码,因为它允许开发人员快速了解所需的依赖关系。
话虽如此,对于您的具体问题@Autowired
而不是@Resource
,但在@Configuration
课程中使用其中任何一个都没有意义。只需使用本地方法参数。