Sunday, 26 August 2012

Spring Autowiring Qualifier Example

Asynchronous Servlet Example                                                           Heap Generation In java

As we know spring beans are singleton by default, but if we need a two or more than two instance then what should we do to achieve this? In context of this solution spring provides a qualifier annotation to create and use two or more than two instances of a bean.

What is Qualifier annotaion
Since autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument.

How to Use it?


<beans xmlns=""
   <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<task:annotation-driven />
 <bean id="emp" class="" />
 <bean id="engineer1" class="" >
  <property name="name" value="agarwalishant1" />
 <bean id="engineer2" class=" Engineer" >
  <property name="name" value="agarwalishant2" />

Employee class 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Employee {
private Engineer  engineer1;
public Engineer getEngineer1() {
return engineer1;

public void setEngineer1( Engineer  engineer1) {
this.engineer1 = engineer1;
private Engineer  engineer2;
public Engineer getEngineer2() {
return engineer2;

public void setEngineer2( Engineer  engineer2) {
this.engineer2 = engineer2;
public String toString() {
return "Employee [Engineer1=" + + ", Engineer2=" + + "]" ;


Engineer Class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

class Engineer
private String name ;
public void setName(String name){ ;
public String getName(){
return name ;

Main class


import org.springframework.context.ApplicationContext;

public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(

Employee emp = (Employee) context.getBean("emp");

So in this example you can see the two instances of the Engineer class but named with different qualifier and
 Employee class will use it and display the desired output.

1 comment:

  1. Hi Ishant,

    I came across your page via facebook. Seems like you have just started writting about Java related stufff. We have a website where people like you share knowledge with others by writing articles(related to Java). Please let me know if you are interested in being editor of our website.

    Please visit our website:

    Ans let us know your views on the same.