Shweta Priyadarshani
Shweta Priyadarshani

Reputation: 258

error creating bean: No qualifying bean, expected single matching bean but found 3

I have a query in Spring MVC I have 4 DAO(data access object) classes for DB related methods 3 of them are child classes and 4th one is parent of all. Say A,B,C,D are 4 classes, A is parent of B,C,D So I annotated all these as @Repository. Now in another class lets say E , i am Autowiring B class as:

Class E {
@Autowired 
B b;
..
..
}

This works fine. Now in another class F, I am doing :

Class F {
@Autowired 
A a;
..
..
}

Now executing this gives error:

No qualifying bean, expected single matching bean but found 3

Now I understood the problem but still not very clear to which basic spring concept this is using which i am missing. Can someone explain in detail. I think i am missing @Qualifier on top of A class. But this A class is not an interface. So what if i need specifically the methods of A class which are not present in child classes. Then how will qualifier help here.

Upvotes: 0

Views: 3729

Answers (1)

John
John

Reputation: 336

Spring by default uses Type of the bean to find a match for autowiring. If more that one bean of the same Type is found in the ApplicationContext, then you'll get an error "expected single matching bean but found 3, A, B, C" . One way to find match using the @Qualifier which finds a Bean by its name.

@Component class A implements DAO {...}
@Component class B implements DAO {...}

class F {
@Autowired
@Qualifier('a') //lowercase "a" will be the default bean name for A
A a;

Another option is to mark @Primary class A then bean A will be autowired and you can omit @Qualifier

Upvotes: 1

Related Questions