问题描述
所以,如果我理解正确的话,如果有多个候选者,两者都是确定哪个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?
推荐答案
阅读作为默认。
Read @Primary
as the "default".
如果bean有 @Autowired
没有任何 @Qualifier
,并且存在多个类型的bean,将选择标记为 @Primary
的候选bean,即它是默认选择当没有其他信息可用时,即 @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
添加到所有现有的bean中 @Autowired
。可以这么说它们是grand来。
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注释之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!