为什么NoUniqueBeanDefinitionException:没有定义类型的限定bean:期望的单个匹配bean但找到2

时间:2014-06-26 12:18:25

标签: java spring beancreationexception

在这个小应用程序中,我使用@Autowired注释和@Qualifier注释来配置依赖项,但仍然会抛出异常,如下所述。

Pizaa课程

public class Pizza {

    private Address deliverydest;

    @Autowired
    @Qualifier("ForPizza")
    public void setDeliverydest(Address deliverydest) {
        this.deliverydest = deliverydest;
    }
}

Spring Context Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <bean id="pizza" class="com.test.Shopping.Pizza" />

    <bean id="Cust1Address" class="com.test.Shopping.Address" />

    <bean id="dest1" class="com.test.Shopping.Address" >
        <qualifier value="ForPizza" />
        <property name="buildingno" value="flat1/door2" />
    </bean>

    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

</beans>

抛出的异常是

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pizza': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.test.Shopping.Pizza.setDeliverydest(com.test.Shopping.Address); nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.test.Shopping.Address] is defined: expected single matching bean but found 2: Cust1Address,dest1

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.test.Shopping.Pizza.setDeliverydest(com.test.Shopping.Address); nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.test.Shopping.Address] is defined: expected single matching bean but found 2: Cust1Address,dest1

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.test.Shopping.Address] is defined: expected single matching bean but found 2: Cust1Address,dest1

为什么Spring不考虑@Qualifier注释来找到具有限定符value="ForPizza"的正确bean dest1

3 个答案:

答案 0 :(得分:3)

尝试将以下内容添加到Spring配置中:

<context:annotation-config/>
<context:component-scan base-package="com.test.Shopping"/>

答案 1 :(得分:1)

尝试将@Qualifier放在参数而不是方法上:

@Autowired
public void setDeliverydest(@Qualifier("ForPizza") Address deliverydest) { ... }

答案 2 :(得分:0)

删除所有注释bean后处理器,然后在xml中添加以下内容。

<context:annotation-config/>