0
votes

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.

1
Did you intentionally exclude your Foo constructor or are you trying to inject a bean into a constructor which does not exist? - Tyler Treat
Missed the constructor. But the constructor is there in the original code. - Arjun

1 Answers

1
votes

I believe the constructor injection should look like this:

<constructor-arg>
    <ref bean="beanA"/>
</constructor-arg>

Or even just

<constructor-arg ref="beanA" />

Also move the @Autowired annotation from FooBar in Foo to the constructor since you're using constructor injection.

Alternatively, you could use field injection by doing this:

<bean id="bean1" class="Foo">
    <property name="a" ref="beanA" />
</bean>