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