【问题标题】:Passing constructors for outer dependency into Guice implementation将外部依赖的构造函数传递给 Guice 实现
【发布时间】:2020-09-15 14:05:11
【问题描述】:

我有一个作业,它应该从深度存储中读取数据。我正在为我的项目使用 Guice DI。

已经编写了一个深度存储,并作为外部依赖项出现。我正在努力在 Guice 中实例化客户端

这里是代码

工作模块

public class JobModule extends AbstractModule {
  private Config config;

  JobModule(Config config) {
     this.config = config;
  }

  @Override
  protected void configure() {
    bind(Reader.class).to(DeepStoreReader.class);
  }

  @Provides
  @Named("config")
  Config provideConfig() {
    return this.config;
  }
}

阅读器界面

public interface Reader {
  List<String> getData(String path);
}

DeepStoreReader

public class DeepStoreReader implements Reader {
  private final DeepStoreClient deepStoreClient;

  DeepStoreReader(@Named("config") Config config) {
     this.deepStoreClient = new DeepStoreClient(config);
  }

  @Override
  public List<String> getData(String path) {
    return this.deepStoreClient.getData(path);
  }
}

问题是我不想在DeepStoreReader 构造函数中实例化DeepStoreClient,因为测试DeepStoreReader 变得很困难,因为我无法模拟DeepStoreClient

在这种情况下,实例化客户端的首选方法是什么? DeepStoreClient 不是 Guice 模块/实现,而是作为外部发布的依赖项出现

PS:我是 DI 和学习 Guice 的新手

【问题讨论】:

    标签: java dependency-injection guice factory


    【解决方案1】:

    你要的是constructor injection,例如:

    @Inject
    public DeepStoreReader(DeepStoreClient deepStoreClient) {
        this.deepStoreClient = deepStoreClient;
    }
    

    Guice 将负责为您实例化 DeepStoreClient

    编辑:

    如果DeepStoreClient本身有依赖,你也可以注解那个构造函数:

    @Inject
    public DeepStoreClient(@Named("config") Config config) {
        // ... 8< ...
    }
    

    【讨论】:

    • 如果 DeepStoreClient 在构造函数中接受参数怎么办?让我编辑示例
    • 但是,DeepStoreClient 是外部发布的依赖项,不是 Guice 模块/实现
    • 在这种情况下,您可能需要考虑改用@Provides
    • 但是,必须在模块中定义提供,并且 DeepStoreClient 非常特定于 DeepStoreReader 实现。这不是与关注点分离相矛盾吗?
    • 如果这是一个问题,您可以为DeepStoreReader 使用私有子模块。 Guice wiki 会有更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多