Instantiating multiple beans of the same class with Spring annotations

后端 未结 6 1564
时光说笑
时光说笑 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 13:00

    Continuing @espen answer, injecting beans with qualifiers and configuring them differently with external values.

    public class Person{
      @Configuration
      public static class PersonConfig{
        @Bean
        //@Qualifier("personOne") - doesn't work - bean qualifier is method name
        public Person personOne() {
            return new Person("Joe", "Smith");
        }
    
        @Bean
        //@Qualifier("personTwo") - doesn't work - bean qualifier is method name
        public Person personTwo(@Value("${myapp.second.lastName}") String lastName) {
            return new Person("Mary", lastName);
        }
      }
      /* blah blah */
    }
    
    @Component
    public class SomePersonReference{
      @Autowired
      @Qualifier("personTwo")
      Person marry;
    }
    

提交回复
热议问题