为了账号安全,请及时绑定邮箱和手机立即绑定

如何为 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 关注
  • 121 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号