Inject list of all beans with a certain interface

2022-09-01 22:59:43

I have a class ( bean) that looks something like that:@Component

@Component
public class EntityCleaner {

    @Autowired
    private List<Cleaner> cleaners;

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

Cleaner is an interface and I have a few cleaners which I want all of them to run (don't mind the order). Today I do something like that:

 @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;
     }
 }

Is there a way to construct this list without defining a special method in the configuration? Just that spring auto-magically find all those classes the implement the interface, create the list and inject it to ?CleanerEntityCleaner


答案 1

Javadoc of says:@Autowired

In case of a Collection or Map dependency type, the container autowires all beans matching the declared value type.

Thus, you can do something like:

@Component
public class SomeComponent {

    interface SomeInterface {

    }

    @Component
    static class Impl1 implements SomeInterface {

    }

    @Component
    static class Impl2 implements SomeInterface {

    }

    @Autowired
    private List<SomeInterface> listOfImpls;
}

答案 2

推荐