亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何為 AutoWired Bean 指定子依賴

如何為 AutoWired Bean 指定子依賴

長風秋雁 2023-03-09 10:38:10
我有一個這樣定義的 Spring 組件:@Componentpublic class SearchIndexImpl implements SearchIndex {    IndexUpdater indexUpdater;    @Autowired    public SearchIndexImpl(final IndexUpdater indexUpdater) {        Preconditions.checkNotNull(indexUpdater);        this.indexUpdater = indexUpdater;    }}以及IndexUpdater接口的兩個實現,例如:@Componentpublic class IndexDirectUpdater implements IndexUpdater, DisposableBean, InitializingBean {}@Componentpublic class IndexQueueUpdater implements IndexUpdater, DisposableBean, InitializingBean {}如果我嘗試SearchIndexImpl像這樣自動連線:@Autowiredprivate SearchIndex searchIndex;我得到以下異常:org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'IndexUpdater' available: expected single matching bean but found 2: indexDirectUpdater,indexQueueUpdater這是預料之中的,因為 Spring 無法判斷要為的構造函數中的參數IndexUpdater自動連接哪個實現。我如何將 Spring 引導到它應該使用的 bean?我知道我可以使用注釋,但這會將索引更新程序硬編碼為實現之一,而我希望用戶能夠指定要使用的索引更新程序。在 XML 中,我可以這樣做:indexUpdaterSearchIndexImpl@Qualifier<bean id="searchIndexWithDirectUpdater" class="SearchIndexImpl">     <constructor-arg index="0" ref="indexDirectUpdater"/></bean>我如何使用 Spring 的 Java 注釋來做同樣的事情?
查看完整描述

1 回答

?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

使用@Qualifier注釋指定要使用的依賴項:


public SearchIndexImpl(@Qualifier("indexDirectUpdater") IndexUpdater indexUpdater) {

    Preconditions.checkNotNull(indexUpdater);

    this.indexUpdater = indexUpdater;

}

請注意,@Autowired自 Spring 4 以來,不需要自動裝配 bean 的 arg 構造函數。


回答你的評論。


要讓將使用 bean 的類定義要使用的依賴項,您可以允許它定義IndexUpdater要注入容器的實例,例如:


// @Component not required any longer

public class IndexDirectUpdater implements IndexUpdater, DisposableBean, InitializingBean {


}


// @Component not required any longer

public class IndexQueueUpdater implements IndexUpdater, DisposableBean, InitializingBean {

}

在 @Configuration 類中聲明 bean:


@Configuration

public class MyConfiguration{


@Bean

public IndexUpdater getIndexUpdater(){

     return new IndexDirectUpdater();

}

SearchIndexImpl由于 .bean 現在將解決依賴 關系IndexUpdater getIndexUpdater()。

在這里,我們使用@Component一個 bean 及其@Bean依賴項。但是我們也可以通過僅使用和刪除3 個類

來允許對要實例化的 bean 進行完全控制:@Bean@Component


@Configuration

public class MyConfiguration{


@Bean

public IndexUpdater getIndexUpdater(){

     return new IndexDirectUpdater();

}


@Bean 

public SearchIndexImpl getSearchIndexFoo(){

     return new SearchIndexImpl(getIndexUpdater());

}


查看完整回答
反對 回復 2023-03-09
  • 1 回答
  • 0 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號