Instantiating multiple beans of the same class with Spring annotations

后端 未结 6 1563
时光说笑
时光说笑 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:47

    I just had to solve a similar case. This may work if you can redefine the class.

    // This is not a @Component
    public class Person {
    
    }
    
    @Component
    public PersonOne extends Person {
       public PersonOne() {
           super("Joe", "Smith");
       }
    }
    
    @Component
    public PersonTwo extends Person {
       public PersonTwo() {
        super("Mary","Williams");
       }
    }
    

    Then just use PersonOne or PersonTwo whenever you need to autowire a specific instance, everywhere else just use Person.

提交回复
热议问题