@Primary 与 @Autowired 与 @Qualifier 注释的区别 [英] Difference between @Primary vs @Autowired with @Qualifier annotations
问题描述
所以,如果我理解正确的话,如果有多个候选者,两者都是确定要自动装配哪个 bean 的方法.那么究竟有什么区别呢?
So, if I understood correctly, both are the way to determine which bean to autowire if there are multiple candidates. So what exactly is the difference?
推荐答案
阅读 @Primary
作为默认".
Read @Primary
as the "default".
如果一个bean有@Autowired
没有任何@Qualifier
,并且存在多个该类型的bean,则标记为的候选bean@Primary
将被选中,即当没有其他信息可用时,即当 @Qualifier
缺失时,它是默认选择.
If a bean has @Autowired
without any @Qualifier
, and multiple beans of the type exist, the candidate bean marked @Primary
will be chosen, i.e. it is the default selection when no other information is available, i.e. when @Qualifier
is missing.
一个很好的用例是,最初您只有一个该类型的 bean,所以没有使用 @Qualifier
的代码.当您添加另一个 bean 时,您还将 @Qualifier
添加到旧 bean 和新 bean,因此任何 @Autowired
都可以选择它想要的.通过将 @Primary
添加到旧的原始 bean,您不必将 @Qualifier
添加到所有现有的 @Autowired
.可以这么说,他们是祖父".
A good use case is that initially you only had one bean of the type, so none of the code used @Qualifier
. When you then add another bean, you then also add @Qualifier
to both the old and the new bean, so any @Autowired
can choose which one it wants. By also adding @Primary
to the old original bean, you don't have to add @Qualifier
to all the existing @Autowired
. They are "grandfathered" in, so to speak.
@Primary
也很好,例如95% 的 @Autowired
想要一个特定的 bean.这样,只有需要其他 bean 的 @Autowired
需要指定 @Qualifier
.这样,您就有了所有自动装配所需的主要 bean,而 @Qualifier
仅用于请求替代"bean.
@Primary
is also good if e.g. 95% of @Autowired
wants a particular bean. That way, only the @Autowired
that wants the other bean(s) need to specify @Qualifier
. That way, you have primary beans that all autowired wants, and @Qualifier
is only used to request an "alternate" bean.
这篇关于@Primary 与 @Autowired 与 @Qualifier 注释的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!