如何在使用注释时声明Spring bean autowire-candidate ="false"?

Naz*_* K. 10 java spring spring-annotations

我正在使用@ComponentScan@Component定义我的春豆.我想要的是声明其中一个bean autowire-candidate=false.

这可以使用xml中的此属性来完成.是不是注释中的等价物?

我想要这个的原因是因为我有2个相同接口的实现,我不想使用@Qualifier.

编辑:使用@Primary是一个有效的解决方案,但autowire候选人在我看来似乎是一个有用的功能与自己的语义.

谢谢

Ser*_*lov 11

看起来Spring拒绝了autowire-candidate=false概念,它不再受支持.没有带注释的模拟,所以@Primary最好的解决方法就像你注意到的那样.

另一种方法是使用自定义org.springframework.beans.factory.support.AutowireCandidateResolver,其中使用的DefaultListableBeanFactory逻辑可以从autowire候选中排除不需要的bean.在这种情况下,该技术将类似于用于autowire-candidate=falseSimpleAutowireCandidateResolver.


Ken*_*han 5

由于春季5.1,您可以配置autowire-candidate@Bean通过 autowireCandidate属性:

@Bean(autowireCandidate = false)
public FooBean foo() {
      return newFooBean();
}
Run Code Online (Sandbox Code Playgroud)