将外部依赖的构造函数传递给 Guice 实现
Passing constructors for outer dependency into Guice implementation
我有一个作业,它应该从深度存储中读取数据。我正在为我的项目使用 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;
}
}
Reader 界面
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 module/implementation,而是作为外部发布的依赖项
PS: 我是 DI 新手,正在学习 Guice
你想要的是constructor injection,例如:
@Inject
public DeepStoreReader(DeepStoreClient deepStoreClient) {
this.deepStoreClient = deepStoreClient;
}
Guice 会负责为您实例化 DeepStoreClient
。
编辑:
如果DeepStoreClient
本身有依赖,也可以注解那个构造函数:
@Inject
public DeepStoreClient(@Named("config") Config config) {
// ... 8< ...
}
我有一个作业,它应该从深度存储中读取数据。我正在为我的项目使用 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;
}
}
Reader 界面
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 module/implementation,而是作为外部发布的依赖项
PS: 我是 DI 新手,正在学习 Guice
你想要的是constructor injection,例如:
@Inject
public DeepStoreReader(DeepStoreClient deepStoreClient) {
this.deepStoreClient = deepStoreClient;
}
Guice 会负责为您实例化 DeepStoreClient
。
编辑:
如果DeepStoreClient
本身有依赖,也可以注解那个构造函数:
@Inject
public DeepStoreClient(@Named("config") Config config) {
// ... 8< ...
}