With an XML configured Spring bean factory, I can easily instantiate multiple instances of the same class with different parameters. How can I do the same with annotations? I would like something like this:
@Component(firstName="joe", lastName="smith")
@Component(firstName="mary", lastName="Williams")
public class Person { /* blah blah */ }
Yes, you can do it with a help of your custom BeanFactoryPostProcessor implementation.
Here is a simple example.
Suppose we have two components. One is dependency for another.
First component:
As you could see, there is nothing special about this component. It has dependency on two different instances of MySecondComponent.
Second component:
It’s a bit more tricky. Here are two things to explain. First one – @Qualifier – annotation which contains names of MySecondComponent beans. It’s a standard one, but you are free to implement your own. You’ll see a bit later why.
Second thing to mention is FactoryBean implementation. If bean implements this interface, it’s intended to create some other instances. In our case it creates instances with MySecondComponent type.
The trickiest part is BeanFactoryPostProcessor implementation:
What does it do? It goes through all beans annotated with @Qualifier, extract names from the annotation and then manually creates beans of this type with specified names.
Here is a Spring config:
Last thing to notice here is although you can do it you shouldn’t unless it is a must, because this is a not really natural way of configuration. If you have more than one instance of class, it’s better to stick with XML configuration.