微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将外部依赖的构造函数传递到Guice实现中

如何解决将外部依赖的构造函数传递到Guice实现中

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

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

这是代码

JobModule

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

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

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

PS:我是DI的新手,正在学习Guice

解决方法

您想要的是constructor injection,例如:

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

Guice将为您实例化DeepStoreClient

编辑:

如果DeepStoreClient本身具有依赖项,则还可以注释该构造函数:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。