Case 3 - Using @Qualifier

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.

  1. Rename the id of the cust_address bean, which we created earlier, as cust_address1.
  2. 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> 
  1. 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()); }
  1. On execution, we will get the following exception specifying there are multiple instances of type Address available for injection leading to ambiguity:
  1. 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.

  1. 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:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.51.241