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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With