[英]@Autowired bean property is null in @Configuration bean
@Configuration bean 中的 @Autowired 屬性有問題。
我有一個類似於下面的豆子:
@Configuration
public class MyConfig {
@Autowired MongoTemplate mongoTemplate;
@Bean
MongoDbMetadataStore indexMetadataStore() {
return new MongoDbMetadataStore(mongoTemplate, "index");
}
}
並且 ... mongoTemplate 在創建 indexMetadataStore bean 時為 null(用調試器檢查)。 不幸的是,我無法提供整個項目結構,它很大(它有大約 5 個 XML 配置文件和大約 20-30 個 @Configuration bean),我敢打賭可能會有循環引用或類似的東西。
然而,這個 mongoTemplate bean 是更早創建的並注入到其他 bean(也用調試器檢查),所以此時 mongoTemplate 已完全創建,我不明白為什么它沒有注入並留空。
我應該在哪里看的任何想法?
好的,我發現了一個問題。 我將在這里描述它,以便其他人可能會發現這個答案有用並節省解決它的寶貴時間:)。
結果證明存在循環引用,Spring 正在盡最大努力初始化和使用未完全初始化的配置對象。 有config1
和config2
bean(都是@Configuration
),它們使用彼此的對象。
有趣的是,在這種情況下,Spring 會嘗試按以下順序初始化@Resource
、 @Autowired
和@Value
:
@Resource
首先初始化,按照對象在@Configuration
bean 中聲明的順序@Value
被視為@Autowired
。 因此, @Value
和@Autowired
在所有@Resource
bean 初始化之后按照出現的順序進行初始化。 理解上述順序很重要,因為您的 bean 和循環引用可能依賴於@Value
設置,並且在創建從其他配置 bean 引用的資源時,此類設置可能仍然為null
。
然而,最好的策略是避免循環引用,最后這就是我所做的 - 將違規資源放到新的第三個配置 bean 中。
訂單聲明似乎是正確的。 我的 @Configuration bean 中有許多 @Autowired 屬性。 嘗試在我的 @Bean 中使用它們時,列表末尾的那些顯示為 null。
@Configuration
public class MyConfig {
@Autowired
private MyClass myClass;
@Autowired
private MyClass2 myClass2;
...
@Autowired
private MyArgument1 myArgument1;
@Autowired
private MyArgument2 myArgument2;
@Bean(name = "myList")
public List<MyInterface> getMyList() { //given MyArgument1 & MyArgument2 implement MyInterface
List<MyInterface> myList= new ArraList<MyInterface>();
myList.add(myArgument1); //resolved as null
myList.add(myArgument2); //resolved as null
return myList;
}
}
如果我把它們放在列表的頂部,它們就會得到正確的解決。 那么..我應該指望正確解決多少? 需要更好的方法。
這是工作
@Configuration
public class MyConfig {
@Autowired
private MyClass myClass;
@Autowired
private MyClass2 myClass2;
...
@Bean(name = "myList")
public List<myInterface> getMyList((@Qualifier("myArgument1") MyInterface myArgument1, (@Qualifier("myArgument2") MyInterface myArgument2) { //given myArgument1 & myArgument 2 are properly labeled as @Component("myArgument1") & @Component("myArgument2")
List<myInterface> myList= new ArraList<myInterface>();
myList.add(myArgument1); //resolved!
myList.add(myArgument2); //resolved!
return myList;
}
}
這似乎實現了正確的依賴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.