0

I have interface A.java and 3 classes which are implementing A.java interface named B.java, C.java and D.java. Now i am try to inject the bean like this.

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
  }
}

It is showing Error message something: "Unique bean not found: contains multiple beans["B","C","D"]".

If I am configuring these beans in XML file, it is working fine but I don't want to use xml config

How to solve this problem Using spring Annonantion??

vinny
  • 1
  • 1
  • Give them unique names. You can't give it three instances of A and ask the Spring bean factory to read your mind. – duffymo Jun 03 '16 at 03:14

1 Answers1

0

It seems to me that the problem is with the Autowired annotation, because it'll do the injection by type, and the type of your variable is A, so It will be difficult to decide which bean to actually inject, B, C or D.

Try to use Resource annotation which decide to inject by name. Or instead just add Qualifier annotation.

Look here for further explanation:

Difference between @Qualifier and @Resource

Community
  • 1
  • 1
Moshe Arad
  • 3,587
  • 4
  • 18
  • 33