Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating multiple beans of the same class with Spring annotations

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 */ } 
like image 229
Francois Avatar asked May 25 '10 05:05

Francois


People also ask

Can we have multiple beans of a same type in a class?

The limitation of this approach is that we need to manually instantiate beans using the new keyword in a typical Java-based configuration style. Therefore, if the number of beans of the same class increases, we need to register them first and create beans in the configuration class.

How do you inject multiple beans of the same type?

The default autowiring is by type, not by name, so when there is more than one bean of the same type, you have to use the @Qualifier annotation.

Can we define two beans with same name in Spring?

Can I define spring bean twice with same name in different bean definition file? Yes. When the second bean definition file loads, it overrides the definition from the first file. The main objective of this behavior is to ovrrride the previously loaded bean definition.


1 Answers

It's not possible. You get a duplicate exception.

It's also far from optimal with configuration data like this in your implementation classes.

If you want to use annotations, you can configure your class with Java config:

@Configuration public class PersonConfig {      @Bean     public Person personOne() {         return new Person("Joe", "Smith");     }      @Bean     public Person personTwo() {         return new Person("Mary", "Williams");     } } 
like image 145
Espen Avatar answered Sep 22 '22 03:09

Espen