Here’s my scenario. I have two classes ClassA and ClassB. ClassB inherits ClassA.
I’m using @Component annotation on both of them to make them Spring beans.
@Component
public class ClassA{
// parent
}
@Component
public class ClassB extends ClassA{
// child
}
public class ClassC{
@Autowired
private ClassA classA;
public void doSomething(){
}
}
Now, whenever I try to use @autowired annotation in ClassC to inject ClassA as shown above, I get the following exception.
No unique bean of type [ClassA] is defined: expected single matching bean but found 2: [classA, classB]
I understand that when auto-wiring by type, spring finds two beans that are assignable to ClassA and so it throws an exception.
Is there an easy way to resolve this problem apart from using @Qualifier annotation and auto-wiring by name?
Could I instruct spring to not only check for a bean that is assignable by type but also check to see if it is the exact same class type?
Yes, use the
@Primaryannotation.If that is unfeasible and you do not want to use @Qualifier, then you will have to resolve it manually. Something like: