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

Mar*_*ski 8 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

点类:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的春天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>
Run Code Online (Sandbox Code Playgroud)

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

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

AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext("spring.xml");
BeanFactory beanFactory = abstractApplicationContext.getBeanFactory();
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

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
Run Code Online (Sandbox Code Playgroud)

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

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

Cos*_*atu 7

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

或者,如果你真的想控制工具,在您的上下文中实例的一切,看看实际的候选人解析器@Qualifier.