In some situations, we may have more than one bean of the same type configured in the container. To have more than one bean is not a problem unless developers control the dependency injection. It may also be possible to have a different id of the dependency, or to have more than one bean of the same type but none of the id match. Let's use @Qualifier to overcome these problems; we will use the same Customer_Autowired class from the previous step.
- Rename the id of the cust_address bean, which we created earlier, as cust_address1.
- Add one more bean of type Address in it, as shown in the following piece of code:
<bean id="address" class="com.ch02.beans.Address"> <property name="build_no" value="2"/> <property name="city_name" value="Pune"/> <property name="pin_code" value="123"/> </bean>
- Create TestCustomer_Autowiring1 to get the customer instance, as follows:
public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context = new
ClassPathXmlApplicationContext("customer_new.xml"); Customer_Autowired customer = (Customer_Autowired) context.getBean("customer_Autowired"); System.out.println(customer.getCust_name() + " " + customer.getCust_id() + customer.getCust_address()); }
- On execution, we will get the following exception specifying there are multiple instances of type Address available for injection leading to ambiguity:
- Update the annotation of the data member cust_address with @Qualifier, as shown in the following lines of code:
@Qualifier(value="address") private Address cust_address;
We specify the id of the bean that we want to inject to fulfill the dependency. In our case, the bean whose id is address will be injected.
- Execute the main function that we created in step 2 to get the following output, which shows beans with id as address gets injected in Customer_Autowired: