我是春季新人。但是尝试基本的东西。根据理论,我应该工作,但是没有工作。我有2个具有不同ID的相同豆。我应该能够@Autowired
拥有唯一的id @Qualifier("PersonBean2")
。但它给错误。我不知道哪里出了什么问题。请通知我?谢谢!
配置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;
}
所有二传手和消气剂均已删除。
测试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]
<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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句