【问题标题】:how to inject the multiple bean in to single referenced variable dynamically using spring annotation如何使用spring注解将多个bean动态注入单个引用变量
【发布时间】:2016-06-03 03:10:41
【问题描述】:

我有接口 A.java 和 3 个实现 A.java 接口的类,名为 B.java、C.java 和 D.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 Annonantion 解决这个问题?

【问题讨论】:

  • 给他们唯一的名字。你不能给它三个 A 的实例,让 Spring bean 工厂读懂你的想法。

标签: spring-annotations


【解决方案1】:

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

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

看这里以获得进一步的解释:

Difference between @Qualifier and @Resource

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2020-07-19
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多