我有一個例子是這樣的是否可以使用在同一個@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