【发布时间】:2014-12-15 23:09:35
【问题描述】:
我有 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;
}
}
还有我的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"
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. Spring看@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
我是 spring 主题的初学者,但我相信 @Qualifier 注释应该可以完成这项工作并确定使用哪个 bean。
【问题讨论】:
-
是的,这应该可以正常工作(尽管使用基于 Java 的配置比您使用的 XML 容易得多)。请发布您正在使用的 Spring 版本,以及 DEBUG 级别的启动日志。
-
你是如何运行应用程序的?通常,您会配置您的记录器(log4j 或 logback)以在 DEBUG 处从
org.springframework输出消息。 -
但是你如何启动它——作为一个 Web 应用程序?使用 Spring Boot?手动使用
main方法? -
它应该工作,我必须查看启动日志以了解上下文,以便弄清楚发生了什么。 FWIW,XML 中的限定符配置似乎总是有点不稳定。
-
哦,我刚刚意识到你有一个 all-XML 配置。添加
<context:annotation-config/>。