0
votes

I created Car class having field of Engine class type annotated with @Autowired. When I use @Qualifer getting following error:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'beans.Engine' available: expected single matching bean but found 2: def,abc

I am using DTD instead of context schema in spring.xml. Below is the xml file:

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN""http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="def" class="beans.Engine">
    <property name="modelYear" value="2015"/>
</bean>

<bean id="abc" class="beans.Engine">
    <property name="modelYear" value="2015"/>
</bean>
<bean id="c" class="beans.Car"/>    
</beans>

Car.java

public class Car {

@Autowired
@Qualifier(value="def")
private Engine engine;

public void printCarData(){
        System.out.println("Engine Model Year  :  "+engine.getModelYear());

}

}

Engine.java

public class Engine {

private String modelYear;

public void setModelYear(String modelYear) {
    this.modelYear=modelYear;
}

public String getModelYear() {
    return modelYear;
}

}

Client.java

public class Client {

public static void main(String [] a){       

    ApplicationContext ap = new ClassPathXmlApplicationContext("resources/spring.xml");

    Car c = (Car)ap.getBean("c");
    c.printCarData();
}

}

1

1 Answers

0
votes

The reason is that you have two beans with the same type beans.Engine.

In the doc api website of NoUniqueBeanDefinitionException,we can see below:

Exception thrown when a BeanFactory is asked for a bean instance for which multiple matching candidates have been found when only one matching bean was expected.

You have two beans with same type,when your project initialize,it do not know to choose which one,thus this exceptions occurs.

<bean id="def" class="beans.Engine">
    <property name="modelYear" value="2015"/>
</bean>

<bean id="abc" class="beans.Engine">
    <property name="modelYear" value="2015"/>
</bean>

In order to solve this,just remove one of them.