簡體   English   中英

將接口類型的集合注入到使用 @Bean 注釋的方法中

[英]Injecting Collection of Interface Type into Method Annotated with @Bean

使用 Spring 並給定幾個實現公共接口的類,我將如何在方法級別使用@Bean注釋引用實現該接口的所有類?

我想檢索所有實現實例,對每個實例應用一些邏輯,然后返回一個托管Map<String, Animal> object 可以注入其他類或組件。

通用接口

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? 
   }

}

任何幫助將不勝感激,謝謝!

試試這種配置。 這里唯一的一點是集合中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

需要利用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> ...)

   }

}

資源:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM