Autowiring with @Qualifier and @Primary Annotations in Springboot
@Autowired is a mechanism by which Spring Boot automatically resolves and injects collaborating beans into your objects. This feature is part of Spring’s inversion of control (IoC) container that manages the lifecycle and configuration of application objects.
eg.
@Autowired
private Person person;
Types of Autowiring
1. No: This mode tells the framework that autowiring is not supposed to be done. It is the default mode used by Spring.
eg.
<bean id="state" class="sample.State">
<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City"></bean>
2. byName: It uses the name of the bean for injecting dependencies.
eg.
<bean id="state" class="sample.State">
<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="byName"></bean>
3. byType: It injects the dependency according to the type of bean.
eg.
领英推荐
<bean id="state" class="sample.State">
<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="byType"></bean>
4. Constructor: It injects the required dependencies by invoking the constructor.
eg.
<bean id="state" class="sample.State">
<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="constructor"></bean>
5. Autodetect: The autodetect mode uses two other modes for autowiring – constructor and byType.
<bean id="state" class="sample.State">
<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="autodetect"></bean>
Dependent Annotations
The @Qualifier and @Primary annotations in Spring serve complementary roles in resolving bean ambiguity during dependency injection.
1. @Qualifier: The @Qualifier annotation is used to resolve ambiguity when multiple beans of the same type are present in a Spring application context. It allows you to specify a specific bean to be injected by using a qualifier value. The @Qualifier annotation is used in conjunction with @Autowired to avoid confusion when we have two or more beans configured for the same type. If there are multiple implementations for a single interface then we can use @Qualifier to choose the required implementation at runtime.
2. @Primary: The @Primary annotation is used to indicate a default bean when multiple beans of the same type are present. If multiple beans are eligible for autowiring and none of them are explicitly specified using @Qualifier, the bean marked with @Primary will be selected by default.