簡體   English   中英

@Configuration 類,將@Bean 傳遞給其他@Bean

[英]@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 beanBOtherCustomType beanC
  • 區分CustomType beanACustomType beanD

...只要它們是相同的類型。 因此,如果沒有限定符,自動裝配CustomType beanA是不安全的。 你有兩個選擇:

  1. 使用@Qualifier自動裝配某個 bean。
  2. 使用@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 **/ 
    }
}

beanBbeanC主體中調用方法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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM