Java Spring:获取特定接口和类型的所有 Bean
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40286047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring: get all Beans of certain interface AND type
提问by Askar Ibragimov
In my Spring Boot application, suppose I have interface in Java:
在我的 Spring Boot 应用程序中,假设我有 Java 接口:
public interface MyFilter<E extends SomeDataInterface>
(a good example is Spring's public interface ApplicationListener< E extends ApplicationEvent >)
(一个很好的例子是 Spring 的公共接口 ApplicationListener< E extends ApplicationEvent >)
and I have couple of implementations like:
我有几个实现,例如:
@Component
public class DesignatedFilter1 implements MyFilter<SpecificDataInterface>{...}
@Component
public class DesignatedFilter2 implements MyFilter<SpecificDataInterface>{...}
@Component
public class DesignatedFilter3 implements MyFilter<AnotherSpecificDataInterface>{...}
Then, in some object I am interested to utilize all filtersthat implement MyFilter< SpecificDataInterface > but NOTMyFilter< AnotherSpecificDataInterface >
然后,在某些对象中,我有兴趣利用实现 MyFilter<SpecificDataInterface>但不是MyFilter<AnotherSpecificDataInterface> 的所有过滤器
What would be the syntax for this?
这将是什么语法?
采纳答案by mh-dev
The following will inject every MyFilter instance that has a type that extends SpecificDataInterface as generic argument into the List.
以下将注入每个 MyFilter 实例,该实例的类型将扩展 SpecificDataInterface 作为泛型参数扩展到 List 中。
@Autowired
private List<MyFilter<? extends SpecificDataInterface>> list;
回答by Issam EL-ATIF
You can simply use
你可以简单地使用
@Autowired
private List<MyFilter<SpecificDataInterface>> filters;
回答by Quang Nguyen
In case you want a map, below code will work. The key is your defined method
如果你想要一张地图,下面的代码将起作用。关键是你定义的方法
private Map<String, MyFilter> factory = new HashMap<>();
@Autowired
public ReportFactory(ListableBeanFactory beanFactory) {
Collection<MyFilter> interfaces = beanFactory.getBeansOfType(MyFilter.class).values();
interfaces.forEach(filter -> factory.put(filter.getId(), filter));
}
回答by magiccrafter
In case you want a Map<String, MyFilter>
, where the key
(String
) represents the bean name:
如果您想要 a Map<String, MyFilter>
,其中key
( String
) 代表 bean 名称:
private final Map<String, MyFilter> services;
public Foo(Map<String, MyFilter> services) {
this.services = services;
}
which is the recommended
alternative to:
这是recommended
替代方案:
@Autowired
private Map<String, MyFilter> services;