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

新手上路,请多包涵

在我的 Spring Boot 应用程序中,假设我有 Java 接口:

 public interface MyFilter<E extends SomeDataInterface>

(一个很好的例子是 Spring 的 公共接口 ApplicationListener< E extends ApplicationEvent >

我有几个实现,例如:

 @Component
public class DesignatedFilter1 implements MyFilter<SpecificDataInterface>{...}

@Component
public class DesignatedFilter2 implements MyFilter<SpecificDataInterface>{...}

@Component
public class DesignatedFilter3 implements MyFilter<AnotherSpecificDataInterface>{...}

然后,在某些对象中,我有兴趣利用 所有 实现 MyFilter< SpecificDataInterface > 但不是 MyFilter< AnotherSpecificDataInterface > 的过滤器

这个的语法是什么?

原文由 onkami 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 981
2 个回答

下面将把每个具有扩展 SpecificDataInterface 类型的 MyFilter 实例作为通用参数注入到列表中。

 @Autowired
private List<MyFilter<? extends SpecificDataInterface>> list;

原文由 mh-dev 发布,翻译遵循 CC BY-SA 3.0 许可协议

你可以简单地使用

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

编辑 2020 年 7 月 28 日:

由于不再建议 使用字段注入,因此应使用构造函数注入而不是字段注入

使用构造函数注入:

 class MyComponent {

  private final List<MyFilter<SpecificDataInterface>> filters;

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

原文由 Issam El-atif 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题