bar
Spring.xml
public class Car {
@Qualifier("e2")
@Autowired
private Engine engine;
public void printData() {
System.out.println("Engine object ref "+engine.getModelOfYear());
}
}
public class Engine {
private String modelOfYear;
public String getModelOfYear() {
return modelOfYear;
}
public void setModelOfYear(String modelOfYear) {
this.modelOfYear = modelOfYear;
}
}
测试课
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="e1" class="beans.Engine">
<property name="modelOfYear" value="2013"/>
</bean>
<bean id="e2" class="beans.Engine">
<property name="modelOfYear" value="2011"/>
</bean>
<bean id="c1" class="beans.Car"/>
</beans>
我总是遇到的例外
引起: org.springframework.beans.factory.NoUniqueBeanDefinitionException:没有 bean类型的限定豆类.Engine&#39;可用:预期单身 匹配bean但找到2:e1,e2 在org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:215) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116) 在org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584) ......还有15个
答案 0 :(得分:2)
您正在将注释与xml配置混合。
您在XML中声明了您的bean Car
,但是通过注释声明了@Qualifier
,因此它不起作用。
替换
<bean id="c1" class="beans.Car"/>
使用:
<bean id="c1" class="beans.Car">
<property name="engine" ref="e2"/>
</bean>
或者完全删除xml配置并使用完全注释(这是首选并现在推荐)
答案 1 :(得分:0)
让Spring处理XML声明bean中的@Autowired
注释,将<context:annotation-config/>
添加到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">
<context:annotation-config/>
<bean id="e1" class="beans.Engine">
<property name="modelOfYear" value="2013"/>
</bean>
<bean id="e2" class="beans.Engine">
<property name="modelOfYear" value="2011"/>
</bean>
<bean id="c1" class="beans.Car"/>
</beans>