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?
The @Primary annotation sets the bean preference and it is used with the @Bean or @Component etc stereotype annotations. On the other hand, @Qualifier is usually used with @Autowired or @Inject etc annotations.
Spring @Primary vs @Qualifier. 3.1. We use @Qualifier in Spring to autowire a specific bean among same type of beans, where as @Primary is used to give high preference to the specific bean among multiple beans of same type to inject to a bean.
The difference are that @Autowired and @Qualifier are the spring annotation while @Resource is the standard java annotation (from JSR-250) . Besides , @Resource only supports for fields and setter injection while @Autowired supports fields , setter ,constructors and multi-argument methods injection.
There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property. In such cases, you can use the @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.
Read @Primary
as the "default".
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With