
There may be a case when you want to create more than one bean of the same Class and want to autowire only one of them with a property. In such cases, you can use the @Qualifier annotation along with @Autowired annotation.
By doing this you will eliminate the confusion as to which bean would be autowired to that property.
Consider the below bean configuration in the xml file.
<bean id = "emp1" class = "com.springsamples.Employee">
<property name = "name" value = "John" />
<property name = "age" value = "30"/>
</bean>
<bean id = "emp2" class = "com.springsamples.Employee">
<property name = "name" value = "David" />
<property name = "age" value = "40"/>
</bean>
<bean id = "emp3" class = "com.springsamples.Employee">
<property name = "name" value = "Neil" />
<property name = "age" value = "35"/>
</bean>
You will see 3 bean objects from the employee class. If you try to autowire an Employee property using @Autowired annotation as below, it would fail as auto wiring would be done basis type and there are 3 candidates for the same.
@Autowired
private Employee emp;
To solve this, we would use the @Qualifier annotation as below.
@Component
public class People {
@Autowired
@Qualifier("emp1")
private Employee emp;
}
Here emp property would be auto wired with the bean of the Employee class having bean id emp1.