[英]Java Config @Bean not autowired in other @Configuration class
[英]@Configuration class, pass @Bean to other @Bean
將同一配置類中存在的@Bean
類型傳遞/使用到另一個@Bean
的最佳方法是什么? 例如,如果我有當前的情況:
@Configuration
public ConfigurationSample {
@Bean("first")
public CustomType beanA(){
}
@Bean("four")
public CustomType beanD(){
}
@Bean("second")
public OtherCustomType beanB(@Qualifier("first") CustomType bean){
//Use bean
}
@Bean("third")
public OtherCustomType beanC(){
CustomType bean = beanA();
....
....
}
}
我應該使用@Qualifier
批注還是我可以直接調用 bean 或者它是等效的,為什么?
編輯
閱讀我之前添加的beanD()
丟失的響應(抱歉!),以更清楚地了解@Qualifier
注釋的需要。
如果您有 2 個相同 bean 的實現,請使用@Qualifier
;
@Configuration
public ConfigurationSample {
@Bean("first")
public CustomType beanA(){
//
}
@Bean("second")
public CustomType beanB(){
//
}
@Bean("third")
public OtherCustomType beanC(@Qualifier("first") CustomType bean){
//Use bean
}
}
在您的情況下,您不需要使用@Qualifier
問題編輯介紹后可進行編輯beanD
。
讓我們說清楚:
CustomType beanA
不依賴任何東西OtherCustomType beanB
依賴於CustomType beanA
OtherCustomType beanC
依賴於CustomType beanA
CustomType beanD
不依賴任何東西因此,您需要做的就是:
OtherCustomType beanB
和OtherCustomType beanC
CustomType beanA
和CustomType beanD
...只要它們是相同的類型。 因此,如果沒有限定符,自動裝配CustomType beanA
是不安全的。 你有兩個選擇:
@Qualifier
自動裝配某個 bean。@Primary
注釋beanA
以定義自動@Primary
中的優先級。 以下代碼段是第一種方式的示例(使用@Qualifier
):
@Configuration
public ConfigurationSample {
@Bean("beanA")
public CustomType beanA() {
/** CODE **/
}
@Bean("beanB")
public OtherCustomType beanB(@Qualifier("beanA") CustomType beanA) {
/** USE beanA HERE **/
}
@Bean("beanC")
public OtherCustomType beanC(@Qualifier("beanA") CustomType beanA) {
/** USE beanA HERE **/
}
@Bean("beanD")
public CustomType beanD(){
/** CODE **/
}
}
在beanB
和beanC
主體中調用方法beanA()
而不是自動裝配也是安全的。
當創建多個相同類型的 bean 並且只想將其中一個與屬性連接時。 在這種情況下,您可以將 @Qualifier 注釋與 @Autowired 一起使用,通過指定將連接的確切 bean 來消除混淆。
就像在 xml 中一樣
<!-- Definition for student1 bean -->
<bean id = "student1" class = "com.test">
<property name = "name" value = "alpha" />
<property name = "age" value = "11"/>
</bean>
<!-- Definition for student2 bean -->
<bean id = "student2" class = "com.test">
<property name = "name" value = "beta" />
<property name = "age" value = "2"/>
</bean>
在課堂里
public class Profile {
@Autowired
@Qualifier("student1")
private Student student;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.