简体   繁体   中英

Inject list of all beans with a certain interface

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

@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 Cleaner interface, create the list and inject it to EntityCleaner ?

Javadoc of @Autowired says:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM