如果您的模块本身将参数作为构造函数,如何注入依赖项?
How to inject dependencies if your module itself take parameters in as a constructor?
我刚刚了解了依赖注入 (DI),并且开始喜欢上它。为了注入依赖项,我使用了 Google Guice 框架。在概念上一切 运行 都很好,但是在编写模块时我想到了如果我的模块需要依赖项作为构造函数怎么办,毕竟它只是一个 class 扩展 AbstractModule。
所以,基本上,我有 3 个模块作为一个整体。
环境模块
public class EnvModule extends AbstractModule {
@Override
protected void configure() {
install(new Servicemodule());
}
}
服务模块
public class ServiceModule extends AbstractModule {
private final boolean isEnabled;
@Override
protected void configure() {
if (isEnabled) {
install (new ThirdModule());
}
}
- ThirdModule(它不接受任何构造函数中的任何参数并有自己的一些绑定)
基本上,服务模块中的变量定义了我的应用程序是否需要安装第三个模块。该变量在应用程序配置文件中定义。那么如何在 ServiceModule 中注入该变量呢?由于字段是最终的,setter注入是不可能的,有没有办法使用构造注入或字段注入来注入值。
我看到以下选项:
使用系统变量:
ServiceModule() {isEnabled = System.getProperty("isThirdModuleEnabled")};
- 直接在 ServiceModule() 构造函数中读取配置文件
使用@Provides:
class ServiceModule ... {
@Provide @Singleton ThirdModuleParam getThirdModuleParam(...) {
//read the config file
ThirdModuleParam res = new ThirdModuleParam();
res.setIsEnabed(...);
return res;
}
}
class ThirdModule {
@Provide SomeThirdModuleClass getIt(ThirdModuleParam param) {
return param.isEnabled() ? new SomeThirdModuleClass() : null;
}
我刚刚了解了依赖注入 (DI),并且开始喜欢上它。为了注入依赖项,我使用了 Google Guice 框架。在概念上一切 运行 都很好,但是在编写模块时我想到了如果我的模块需要依赖项作为构造函数怎么办,毕竟它只是一个 class 扩展 AbstractModule。 所以,基本上,我有 3 个模块作为一个整体。
环境模块
public class EnvModule extends AbstractModule { @Override protected void configure() { install(new Servicemodule()); } }
服务模块
public class ServiceModule extends AbstractModule { private final boolean isEnabled; @Override protected void configure() { if (isEnabled) { install (new ThirdModule()); } }
- ThirdModule(它不接受任何构造函数中的任何参数并有自己的一些绑定)
基本上,服务模块中的变量定义了我的应用程序是否需要安装第三个模块。该变量在应用程序配置文件中定义。那么如何在 ServiceModule 中注入该变量呢?由于字段是最终的,setter注入是不可能的,有没有办法使用构造注入或字段注入来注入值。
我看到以下选项:
使用系统变量:
ServiceModule() {isEnabled = System.getProperty("isThirdModuleEnabled")};
- 直接在 ServiceModule() 构造函数中读取配置文件
使用@Provides:
class ServiceModule ... { @Provide @Singleton ThirdModuleParam getThirdModuleParam(...) { //read the config file ThirdModuleParam res = new ThirdModuleParam(); res.setIsEnabed(...); return res; } } class ThirdModule { @Provide SomeThirdModuleClass getIt(ThirdModuleParam param) { return param.isEnabled() ? new SomeThirdModuleClass() : null; }