Spring @Autowire two beans of the same class which are not defined in ApplicationContext

autowired, dependency-injection, spring

Solution

You can give qualifiers to the beans:

@Service("contractList")
public class DefaultContractList implements ContractList { ... }

@Service("correctContractList")
public class CorrectContractList implements ContractList { ... }

And use them like this:

public class MyClass {

    @Autowired
    @Qualifier("contractList")
    private ContractList contractList;

    @Autowired
    @Qualifier("correctContractList")
    private ContractList correctContractList;
}

In xml config still using `@Autowired` this would be:

<beans>
    <bean id="contractList" class="org.example.DefaultContractList" />
    <bean id="correctContractList" class="org.example.CorrectContractList" />

    <!-- The dependencies are autowired here with the @Qualifier annotation -->
    <bean id="myClass" class="org.example.MyClass" />
</beans>

Problem

I am working on Spring MVC app and encountered a problem. I am new to Spring, so please forgive me if my working is a bit clumsy. Basically I have a java class ContractList. In my application I need two different objects of this class (both of them must be singleton) ``` public class MyClass { @Autowired private ContractList contractList; @Autowired private ContractList correctContractList; .. do something.. } ``` Note that both of these beans are not defined in ApplicationContext.xml. I am using only annotations. So when I try to access them - contractList and correctContractList end up referring to the same object. Is there a way to somehow differentiate them without defining them explicitly in ApplicationContext.xml ?

Original source