我有一个例子是这样的是否可以使用在同一个@Configuration类中定义的@Resource实例?
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;
}
}
难道是因为我确定在同一个@Configuration
类@Bean
?
如果你在'b''字段中替换'@ Autowired'的'@ Resource'注解,我猜它可以正常工作吗? –
@XtremeBiker好耶,工作。你能把它作为答案发布吗? – OscarRyz