簡體   English   中英

Spring:獲取特定接口和類型的所有 Bean

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

在我的 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> 的所有過濾器

這將是什么語法?

以下將注入每個 MyFilter 實例,該實例的類型將擴展 SpecificDataInterface 作為泛型參數擴展到 List 中。

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

你可以簡單地使用

@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;
  }
  ...
}

如果你想要一張地圖,下面的代碼將起作用。 關鍵是你定義的方法

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

如果您需要Map<String, MyFilter> ,其中key ( String ) 表示 bean 名稱:

private final Map<String, MyFilter> services;

public Foo(Map<String, MyFilter> services) {
  this.services = services;
}

這是recommended替代方案:

@Autowired
private Map<String, MyFilter> services;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM