将接口类型的集合注入到@Bean

时间:2019-10-01 21:57:16

标签: java spring

使用Spring并提供几个实现公共接口的类,我将如何在方法级别使用@Bean批注引用实现该接口的所有类?

我想检索所有实现的实例,对每个实例应用一些逻辑,然后返回可以插入到其他类或组件中的托管Map<String, Animal>对象。

常用接口

public interface Animal {

   String makeNoise();

}
public interface Person {

   String getOccupation();

}

动物实施#1

public Dog implements Animal {

   @Override
   String makeNoise() {
      return "Bark! Bark!";
   }

} 

动物实施#2

public Cat implements Animal {

   @Override
   String makeNoise() {
      return "Meow! Meow!";
   }

} 

人员实施#1

public Developer implements Person {

   @Override
   public String getOccupation() {
      return "Software Engineer";
   }

}

人员实施#2

public Lawyer implements Person {

   @Override
   public String getOccupation() {
      return "Litigator";
   }

}

配置

@Configuration
public class Initialize {

   //<snip> Beans created for Developer, and Lawyer objects </snip>

   @Bean
   Map<String, Developer> getDevelopers(List<Developer> developers) { // This is fine
      return new HashMap<>(...);
   }

   @Bean
   Map<String, Lawyer> getLawyers(List<Person> people) { // Spring wires this dependency fine
      return new HashMap<>(...);
   }

   @Bean
   Map<String, Dog> getOwners(Map<String, Person> owners) { // Spring reports it cannot auto-wire this dependency
                                                            // what do I do here? 
   }

}

任何帮助将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:0)

尝试这种配置。这里唯一的一点是,集合中bean的顺序是随机的,不能受到控制。

    @Configuration
    public class CollectionConfig {

        @Bean
        public Animal getCat() {
            return new Cat();
        }

        @Bean
        public Animal getDog() {
            return new Dog();
        }

        @Bean
        Map<String, Animals> gatherAnimals(List<Animals> animals) {
           // any code
        }
    }

关于https://www.baeldung.com/spring-injecting-collections

的更多信息

答案 1 :(得分:0)

需要利用List的协方差。请参见下面的伪代码/代码段。

@Configuration
public class Initialize {

   //<snip> Beans created for Developer, and Lawyer objects </snip>

   @Bean
   Map<String, Developer> getDevelopers(List<Developer> developers) {
      return new HashMap<>(...);
   }

   @Bean
   Map<String, Lawyer> getLawyers(List<Person> people) {
      return new HashMap<>(...);
   }

   @Bean
   Map<String, Dog> getOwners(List<Map<String, ? extends Person>> owners) { // Spring will auto-wire the "owners" variable 
                                                                            // with all bean objects that match this signature 
                                                                            // (✅ Map<String, Lawyer>, ✅ Map<String, Developer> ...)

   }

}

资源: