簡體   English   中英

具有混合構造函數的 Spring 自動裝配 bean

[英]Spring autowiring bean with mixed constructor

我有兩個這樣的豆子:

@Component
@Scope("prototype")
class A {
    A(int number, B anotherBean) {
         //...
    }
}

@Component
class B {
     //..
}

如何構建 A 並自動裝配 B? 如果我使用 new 我不會得到 anotherBean 的值,如果我使用自動裝配我不會得到 number 的值。

編輯:這個數字是在運行時計算的,所以我不能像建議的答案一樣使用@Value。

利用@Value並通過屬性注入數字的值。 你的ClassA應該看起來像

@Component
@Scope("prototype")
class A {

    @Autowired
    A(@Value("${some.property}")int number, B anotherBean) {
       //...
    }
}

編輯(發布數字運行時值的附加條件)

您可以從BeanFactory.getBeans方法中獲取 bean,正如M.Deinum在注釋中正確指出的那樣。

我今天發現這個問題正在尋找自己的答案。 經過一番考慮,這是我認為我要采用的解決方案。 基本上,我將工廠方法烘焙到 bean 的類中。 這樣做的優點是將“內部”依賴項(在本例中為 B)全部保留在“A”類中,並且對調用者隱藏,同時仍然允許使用調用者的運行時值創建原型。 並且它不需要另一個僅用於工廠方法的類文件。

public class A {

  private A (int number, B otherBean) {
  ...
  }

  @Configuration
  public static class BeanConfig {

    @Autowired
    private B otherBean;

    @Bean
    @Scope("prototype")
    public A makeA(int number) {
      return new A(number, otherBean);
    }
  }
}

然后你可以請求一個原型 bean 實例,同時只提供運行時值:

applicationContext.getBean(A.class, 1);

您需要將所需的要使用的構造函數注釋為 @Autowired,以及您可以通過 Google 搜索找到的其他方法。 至於您的“數字”問題,也有一些方法可以使用注釋來設置參數值,通過 Google 搜索也不難找到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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