我是春天的新人。但尝试基本的东西。根据理论我应该工作,它不起作用。我有2个不同id的相同bean。我应该能够@Autowired
使用唯一身份@Qualifier("PersonBean2")
。但它给出了错误。我不知道哪里出了什么问题。请通知我?谢谢!
config springBeans.xml在哪里: -
<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-2.5.xsd">
<bean
class="org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor"/>
<bean id="customer" class="com.mkyong.common.Customer" >
<property name="action" value="buy" />
<property name="type" value="1" />
</bean>
<bean id="PersonBean1" class="com.mkyong.common.Person">
<property name="name" value="mkyong1" />
<property name="address" value="address 1" />
<property name="age" value="28" />
</bean>
<bean id="PersonBean2" class="com.mkyong.common.Person">
<property name="name" value="mkyong2" />
<property name="address" value="address 2" />
<property name="age" value="28" />
</bean>
</beans>
Customer.java: -
public class Customer {
@Autowired
@Qualifier("PersonBean2")
private Person person;
private int type;
private String action;
}
Person.java: -
public class Person {
private String name;
private String address;
private int age;
}
删除所有setter和getter。
测试app.java: -
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"SpringBeans.xml");
Customer cust = (Customer) context.getBean("customer");
System.out.println(cust);
}
}
错误: -
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customer': Autowiring of fields failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mkyong.common.Person com.mkyong.common.Customer.person;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.mkyong.common.Person] is defined: expected single matching bean but found 2: [PersonBean1, PersonBean2]
答案 0 :(得分:0)
它应该工作!似乎@Qualifier注释没有按预期工作。
仔细检查是否正在从包org.springframework.beans.factory.annotation中导入@Qualifier注释
答案 1 :(得分:0)
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
您添加了AutowiredAnnotationBeanPostProcessor
,顾名思义,它只处理@Autowired
注释。而不是直接使用处理器添加<context:annotation-config />
,这会添加额外的处理器,同时考虑@Qualifier
。
<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">
<context:annotation-config />
另一个提示更喜欢无版本架构spring-beans.xsd
而不是版本化架构spring-beans-2.5.xsd
。