我对这个注释有疑问。
这是我的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中添加了标签,所以我不明白我的程序有什么问题。有人可以向我解释一下吗?
答案 0 :(得分:3)
我想你错过了
<context:annotation-config />
在您的spring-context 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">
答案 1 :(得分:1)
问题出在限定符@Qualifier("circleRelated")
中,因为你试图绑定一个名为circleRelated的bean,但在你的spring-conf.xml中你只声明了3个名字:pointA,pointB,pointC,so它无法匹配并注入实例,因此要么将@Qualifier("circleRelated")
更改为@Qualifier("pointA")
,要么使用<bean id="circleRelated" class="com.majewski.javabrains.Point">