I have a Circle class:
public class Circle { @Autowired @Qualifier("pointA") private Point center; public Point getCenter() { return center; } public void setCenter(Point center) { this.center = center; } }
point class:
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; } }
And my 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>
As far as I know, this should work as follows: 1. spring see @Autowire annotation 2. spring realizes that there are many beans like Point 3. spring uses the @Qualifier annotation to determine which bean to enter
Unfortunately, it does not work like that. Performing:
AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext("spring.xml"); BeanFactory beanFactory = abstractApplicationContext.getBeanFactory();
I get an error message:
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
I start on the topic of spring, but I believe that the @Qualifier annotation should complete the task and determine which bean to use.
Launch Log: https://gist.github.com/mmajews/384207ee97b2cc8bd49a
java spring
Marcin majewski
source share