Instantiating multiple beans of the same class with Spring annotations

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

    Should you need to inject, in the new created object, beans or properties from the spring context, you can have a look at the following section of code in which I have extended the Espen answer by injecting a bean which is created from the spring context:

    @Configuration
    public class PersonConfig {
    
    @Autowired 
    private OtherBean other;
    
    @Bean
    public Person personOne() {
        return new Person("Joe", "Smith", other);
        }
    }
    

    Have a look at this article for all the possibile scenarios.

提交回复
热议问题