我对此注释有疑问。

这是我的Circle课程:

public class Circle implements Shape {

    private Point center;

    public Point getCenter() {
        return center;
    }

    @Autowired
    @Qualifier("circleRelated")
    public void setCenter(Point center) {
        this.center = center;
    }

    @Override
    public void draw() {
        System.out.println("Drawing cicrle " + center.getX() + ", " + center.getY());
    }
}


这是我的spring.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"
    xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="pointA" class="com.majewski.javabrains.Point">
        <qualifier value="circleRelated" />
        <property name="x" value ="0" />
        <property name="y" value ="0" />
    </bean>

    <bean id="pointB" class="com.majewski.javabrains.Point">
        <property name="x" value ="0" />
        <property name="y" value ="1" />
    </bean>

    <bean id="pointC" class="com.majewski.javabrains.Point">
        <property name="x" value ="0" />
        <property name="y" value ="20" />
    </bean>

    <bean id="circle" class="com.majewski.javabrains.Circle" />

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

</beans>


这是我的主要方法:

public static void main(String[] args) {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        context.registerShutdownHook();

        Shape shape = (Shape) context.getBean("circle");
        shape.draw();
    }


我收到一个错误:

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 method:
    public void com.majewski.javabrains.Circle.setCenter(com.majewski.javabrains.Point);
    nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.majewski.javabrains.Point] is defined:
    expected single matching bean but found 3: pointA,pointB,pointC


我已经在“ pointA” bean中添加了选项卡,所以我不明白我的程序出了什么问题。有人可以向我解释吗?

最佳答案

我想你不见了

<context:annotation-config  />


因此,在您的Spring上下文中,XML和@Qualifier("circleRelated")将被忽略。

-编辑-

当然,为了使用它,您需要扩展名称空间定义...

<beans
    ...
    xmlns:context="http://www.springframework.org/schema/context"
    ...
  xsi:schemaLocation=".... http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-YOUR-SPRING-VERSION-HERE.xsd">

关于java - Autowired和Qualifier Java批注,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32113248/

10-10 15:54