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 ?
You can give qualifiers to the beans:
And use them like this:
In xml config still using
@Autowired
this would be:In the case that you don't have access to the class annotated with
@Autowired
there may be another thing you can do. You might be able to take advantage of the@Primary
annotation if the stars align in your favor.Assume you have a library class you can't modify:
And another class that you do control:
Setup your config like so, and it should work:
And annotate
MyClass
withQualifier
to tell it to usemyService
.LibraryClass
will use the bean annotated with@Primary
andMyClass
will use the other with this configuration:This is a rare use, but I used it in a situation where I had my own class that needed to use a legacy implementation as well as a new implementation.