Instantiating multiple beans of the same class with Spring annotations

后端 未结 6 1571
时光说笑
时光说笑 2020-12-02 12:15

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?

6条回答
  •  时光说笑
    2020-12-02 12:55

    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");
        }
    }
    

提交回复
热议问题