[英]Inject list of all beans with a certain interface
I have a class ( @Component
bean) that looks something like that: 我有一个看起来像这样的类(
@Component
bean):
@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
? 只是那个春天自动实现了
Cleaner
接口的所有那些类,创建列表并将其注入EntityCleaner
?
Javadoc of @Autowired
says: @Autowired
Javadoc说:
In case of a Collection or Map dependency type, the container autowires all beans matching the declared value type.
如果是Collection或Map依赖项类型,则容器将自动装配与声明的值类型匹配的所有bean。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.