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 ?Cleaner
EntityCleaner