Spring在非常简单的程序中忽略了@Qualifier

时间:2014-12-15 23:09:36

标签: java spring

我有Circle课程:

public class Circle
{
    @Autowired
    @Qualifier("pointA")
    private Point center;

    public Point getCenter()
    {
        return center;
    }
    public void setCenter(Point center)
    {
        this.center = center;
    }
}

点类:

public class Point
{
    private int x;
    private int y;

    public int getX()
    {
        return x;
    }
    public void setX(int x)
    {
        this.x = x;
    }
    public int getY()
    {
        return y;
    }
    public void setY(int y)
    {
        this.y = y;
    }
}

我的春天xml:

<?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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd"
        >

       <bean id="pointA"  name="pointA" class="SpringTest.Point">
            <qualifier value="pointA"/>
            <property name="x" value="4"/>
            <property name="y" value="4"/>
       </bean>

       <bean id="pointB" name="pointB" class="SpringTest.Point">
              <property name="x" value="2"/>
              <property name="y" value="5"/>
       </bean>

       <bean id="circle" class="SpringTest.Circle">
       </bean>

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

</beans>

就我而言,这应该是这样的: 1.春天看@Autowire注释 2. Spring意识到Point类型有很多bean 3. Spring使用@Qualifier注释来确定要注入的bean

不幸的是,它不是那样的。 执行时:

AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext("spring.xml");
BeanFactory beanFactory = abstractApplicationContext.getBeanFactory();

我收到错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'circle': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private SpringTest.Point SpringTest.Circle.center; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [SpringTest.Point] is defined: expected single matching bean but found 2: pointA,pointB

我是春季主题的初学者,但我相信@Qualifier注释应该完成这项工作并确定使用哪个bean。

启动日志: https://gist.github.com/mmajews/384207ee97b2cc8bd49a

2 个答案:

答案 0 :(得分:7)

您需要在spring xml中添加<context:annotation-config/>,而不是实例化AutowiredAnnotationBeanPostProcessor,因为它不会处理@Qualifier注释。

或者,如果您真的想要控制在上下文中实例化的所有内容,请查看@Qualifier的实际candidate resolver

答案 1 :(得分:-3)

您必须将Point center公开:

public Point center;

Spring只能访问公共属性和方法。