Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject list of all beans with a certain interface

Tags:

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?

like image 987
Avi Avatar asked Dec 02 '18 09:12

Avi


1 Answers

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;
}
like image 143
Aleksandr Semyannikov Avatar answered Oct 04 '22 23:10

Aleksandr Semyannikov