@Qualifier(“ id”)现在正在工作。它显示
没有可用的'beans.Engine_AutoAnno'类型的合格Bean:预期 单个匹配的Bean,但发现2:e,e1
这是我的Engine_AutoAnno.java
package beans;
public class Engine_AutoAnno {
private String model;
public void setModel(String model) {
this.model = model;
}
public String getModel() {
return model;
}
}
这是我的Car_AutoAnno.java
package beans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Car_AutoAnno {
@Autowired
@Qualifier("e")
private Engine_AutoAnno engine;
public void printCar() {
System.out.println("Car engine: "+engine.getModel());
}
}
这是我的主类Client_autoAnno.java
package testMain;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.Car_AutoAnno;
public class Client_autoAnno {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("resource/spring_autowireAnno.xml");
Car_AutoAnno car = (Car_AutoAnno) app.getBean("c");
car.printCar();
}
}
这是我的XML文件:
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- activate autowire annotation -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="c" class="beans.Car_AutoAnno"/>
<bean id="e" class="beans.Engine_AutoAnno">
<property name="model" value="XF"/>
</bean>
<bean id="e1" class="beans.Engine_AutoAnno">
<property name="model" value="XJ"/>
</bean>
</beans>
这是我得到的例外:
线程“主”中的异常 org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名称为'c'的bean时出错:表达了不满意的依赖性 通过现场“引擎”;嵌套异常为 org.springframework.beans.factory.NoUniqueBeanDefinitionException:否 类型为“ beans.Engine_AutoAnno”的合格bean:可用 单个匹配的Bean,但发现2:e,e1
该如何解决?
非常感谢。
答案 0 :(得分:1)
在您的xml @Qualifier注释中添加<context:annotation-config />
。
<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" xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config />
// your bean definations here.
答案 1 :(得分:1)