3

この小さなアプリでは、@Autowiredアノテーションと一緒に@Qualifierアノテーションを使用して依存関係を構成しましたが、以下で説明するように例外がスローされます。

ピザークラス

public class Pizza {

    private Address deliverydest;

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

Spring コンテキスト構成

<?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

.

修飾子を持つ@Qualifier正しい Bean dest1を見つけるために、Spring がアノテーションを考慮しないのはなぜvalue="ForPizza"ですか?

4

3 に答える 3

3

Spring 構成に以下を追加してみてください。

<context:annotation-config/>
<context:component-scan base-package="com.test.Shopping"/>
于 2014-06-26T12:21:49.680 に答える
1

@Qualifierメソッドではなくパラメーターに配置してみてください。

@Autowired
public void setDeliverydest(@Qualifier("ForPizza") Address deliverydest) { ... }
于 2014-06-26T12:31:44.873 に答える