gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:53:10 24 4
gpt4 key购买 nike

我有 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注解来决定注入(inject)哪个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。

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

最佳答案

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

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

关于java - Spring在非常简单的程序中忽略@Qualifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27494819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com