注入具有特定接口的所有bean的列表

时间:2018-12-02 09:50:55

标签: java spring dependency-injection

我有一个看起来像这样的类(@Component bean)

@Component
public class EntityCleaner {

    @Autowired
    private List<Cleaner> cleaners;

    public void clean(Entity entity) {
         for (Cleaner cleaner: cleaners) {
             cleaner.clean(entity);
         }
    }
}

Cleaner是一个界面,我有几个我希望它们都运行的清洁器(不要介意顺序)。今天我要做这样的事情:

 @Configuration
 public class MyConfiguration {
     @Bean
     public List<Cleaner> businessEntityCleaner() {
         List<Cleaner> cleaners = new ArrayList<>();
         cleaners.add(new Cleaner1());
         cleaners.add(new Cleaner2());
         cleaners.add(new Cleaner3());
         // ... More cleaners here

         return cleaners;
     }
 }

有没有一种方法可以构造此列表,而无需在配置中定义特殊方法?只是那个春天自动实现了Cleaner接口实现的所有类,创建了列表并将其注入到EntityCleaner中?

1 个答案:

答案 0 :(得分:2)

@Autowired的Javadoc说:

  

对于Collection或Map依赖项类型,容器   自动装配与声明值类型匹配的所有bean。

因此,您可以执行以下操作:

@Component
public class SomeComponent {

    interface SomeInterface {

    }

    @Component
    static class Impl1 implements SomeInterface {

    }

    @Component
    static class Impl2 implements SomeInterface {

    }

    @Autowired
    private List<SomeInterface> listOfImpls;
}