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 */ }
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.
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 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.
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"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With