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());
}
添加回答
舉報