如何向提供商注入系列



我的应用程序具有一个名为Gateway的类和一个带有这些网关的JSON文件。我已经解析了这个JSON,给了我一个设定的对象。现在,我想创建一个多启示夹,以在我的代码中注入该集合。到目前为止,我创建了这个提供商:

public class GatewaysProvider implements Provider<Set<Gateway>> {
@Override
public Set<Gateway> get() {
    try {
        File file = new File(getClass().getResource("/gateways.json").toURI());
        Type listType = new TypeToken<Set<Gateway>>(){}.getType();
        return new Gson().fromJson(new FileReader(file), listType);
    } catch (URISyntaxException | FileNotFoundException e) {
        e.printStackTrace();
    }
    return new HashSet<>();
}

}

我还应该做些什么才能在我的代码中的任何地方注入此集合:

Set<Gateways> gateways;
@Inject
public AppRunner(Set<Gateway> gateways) {
    this.gateways = gateways;
}

您需要的是依赖项注入机制的实现。

您可以自己做,但我建议您使用存在的di库,例如Easydi

请继续以下步骤:

  1. 添加 easydi 到您的类路径。使用 maven 是:

    <dependency>
        <groupId>eu.lestard</groupId>
        <artifactId>easy-di</artifactId>
        <version>0.3.0</version>
    </dependency>
    
  2. 为您的网关添加包装类型设置,并相应地调整提供商

    public class GatewayContainer {
      Set<Gateway> gateways;
      public void setGateways(Set<Gateway> gateways) {
        this.gateways = gateways;
      }
    }
    public class GatewayProvider implements Provider<GatewayContainer> {
      @Override
      public GatewayContainer get() {
          try {
              File file = new File(getClass().getResource("/gateways.json").toURI());
              Type listType = new TypeToken<Set<Gateway>>() {
              }.getType();
              Set<Gateway> set = new Gson().fromJson(new FileReader(file), listType);
              GatewayContainer container = new GatewayContainer();
              container.setGateways(set);
              return container;
          } catch (URISyntaxException | FileNotFoundException e) {
              e.printStackTrace();
          }
          return new GatewayContainer();
      }
    }
    
  3. 配置并使用您的上下文:

    public class AppRunner {
      GatewayContainer container;
      public AppRunner(GatewayContainer container) {
          this.container = container;
      }
      public static void main(String[] args) {
          EasyDI context = new EasyDI();
          context.bindProvider(GatewayContainer.class, new GatewayProvider());
          final AppRunner runner = context.getInstance(AppRunner.class);
      }
    }
    

之后,您将获得所有注射依赖项的批准

注意:没有任何类型的@Inject(或类似(注释的用法,因为EasyDi默认不需要

不需要它

最新更新