如何使用spring注释将多个bean动态地注入到单个引用的变量中



我有接口A.java和3个类,它们正在实现名为B.java、C.java和D.java的A.java接口。现在我尝试像这样注入bean。

interface A{}
@Component
@Scope("request")
class B implements A{
//......
}
@Component
@Scope("request")
class C implements A{
//.....
}
@Component
@Scope("request")
class D implements A{
}
class Implementation{
@Autowired
public A obj;
@Autowired
private BeanFactory beanFactory;
String[] beans = {"B","C","D"}; //actually these are coming from database in my case
for(String beanName : beans){
obj = (A)beanFactory.getBean(beanName);
....//calling some method of particular bean class
}
}

它显示错误消息:"未找到唯一的bean:包含多个bean["B"、"C"、"D"]"。

如果我在XML文件中配置这些bean,它可以正常工作,但我不想使用XML配置

如何使用spring annonation来解决这个问题??

在我看来,问题出在Autowired注释上,因为它将按类型进行注入,而变量的类型是A,所以很难决定实际注入哪个bean,B、C或D。

尝试使用资源注释,该注释决定按名称注入。或者只添加限定符注释。

查看此处以获得进一步的解释:

@Qualifier和@Resource 之间的差异

最新更新