I have a usecase for which I cannot use the Qualifier annotation (atleast according to my understanding) but I still need to resolve between two beans for Autowire. I cannot use the Qualifier because I dont know which implementation of FooBar will be used inside class Foo. Here is the setup I have:
class Foo
{
@Autowired
private FooBar a;
public Foo(FooBar aa) {a = aa; }
}
interface FooBar
{}
class FooBarA implements FooBar
{}
class FooBarB implements FooBar
{}
spring config:
<bean id="beanA" class="FooBarA"/>
<bean id="beanB" class="FooBarB"/>
<bean id="bean1" class="Foo">
<constructor-arg><ref bean="beanA"/></constructor-arg>
</bean>
<bean id="bean2" class="Foo">
<constructor-arg><ref bean="beanB"/></constructor-arg>
</bean>
This throws an error saying it cannot resolve the bean for the variable “a” in class “Foo” because there are two beans (beanA and beanB) even though I have explicitly specified which derivation of FooBar to use in each case of bean1 and bean2.
I believe the constructor injection should look like this:
Or even just
Also move the
@Autowiredannotation fromFooBarinFooto the constructor since you’re using constructor injection.Alternatively, you could use field injection by doing this: