简体   繁体   English

Spring:获取特定接口和类型的所有 Bean

[英]Spring: get all Beans of certain interface AND type

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 filters that implement MyFilter< SpecificDataInterface > but NOT MyFilter< AnotherSpecificDataInterface >然后,在某些对象中,我有兴趣利用实现 MyFilter<SpecificDataInterface>但不是MyFilter<AnotherSpecificDataInterface> 的所有过滤器

What would be the syntax for this?这将是什么语法?

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;

You can simply use你可以简单地使用

@Autowired
private List<MyFilter<SpecificDataInterface>> filters;

Edit 7/28/2020: 2020 年 7 月 28 日编辑:

As Field injection is not recommended anymore Constructor injection should be used instead of field injection由于不再推荐使用字段注入,因此应使用构造函数注入代替字段注入

With constructor injection:使用构造函数注入:

class MyComponent {

  private final List<MyFilter<SpecificDataInterface>> filters;

  public MyComponent(List<MyFilter<SpecificDataInterface>> filters) {
    this.filters = filters;
  }
  ...
}

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));
}

In case you want a Map<String, MyFilter> , where the key ( String ) represents the bean name:如果您需要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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM