Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between @Primary vs @Autowired with @Qualifier annotations

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?

like image 774
Maciaz Avatar asked Jan 25 '18 16:01

Maciaz


People also ask

What is difference between @primary and @qualifier annotation?

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.

What is the difference between @primary and @qualifier in Spring?

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.

What is the difference between @qualifier and Autowired?

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.

What is the actual use of @autowired @qualifier @component annotation?

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.


1 Answers

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.

like image 184
Andreas Avatar answered Sep 19 '22 05:09

Andreas