Monday, 17 August 2015

Spring Autowiring @Qualifier

There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property, in such case you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [spring.core.qualifier.PastInformation] is defined: expected single matching bean but found 2: two,one at at at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject( ... 15 more

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

       default-autowire="byName" default-autowire-candidates="*">

       <context:annotation-config />

       <bean id="employee" class="spring.core.qualifier.Employee">
              <property name="id" value="1"></property>
              <property name="name" value="Rajesh kumar"></property>
              <property name="profile" value="developer"></property>

       <bean id="two" class="spring.core.qualifier.PastInformation">
              <property name="lastCompany" value="ABC2"></property>
       <bean id="one" class="spring.core.qualifier.PastInformation">
              <property name="lastCompany" value="ABC1"></property>

package spring.core.qualifier;
public class PastInformation {
       private String lastCompany;

       public void displayInfo(String seq) {
              String empDetails = seq + " : "+lastCompany;

       /* setters and getters */

package spring.core.qualifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Employee {

       private PastInformation lastOne;

       private PastInformation lastSecond;

       private int id;

       private String name;

       private String profile;

       public void displayInfo() {
              String empDetails = "id : "+id+" name :"+name+" profile : " + profile;
    /* setters and getters */

package spring.core.qualifier;
import org.springframework.context.ApplicationContext;
public class TestIOC {
       private static ApplicationContext appContext;
       public static void main(String[] args) {
              appContext = new ClassPathXmlApplicationContext     
              Employee empl1 = appContext.getBean("employee", Employee.class);

first: ABC1
last: ABC2
id: 1 name : Rajesh kumar profile: developer

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...