是否可以向模块注入价值

Is it possible to inject value to modules

我有一个模块使用标志来决定是否安装另一个模块。有没有一种方法可以通过注入来实现,或者我是否需要在 ctor 中显式传递标志的值?

 public class MyModule implements Module {

    private final Boolean shouldInstallOtherModule;

    @Inject public MyModule(Boolean shouldInstallOtherModule) {
        this.shouldInstallOtherModule = shouldInstallOtherModule;
    }

    public void configure() {
      if(shouldInstallOtherModule) {
       install(SomeOtherModule);       
       }

    }
}

虽然可以注入模块,或从注入器获取模块,但更好的设计决定是:模块可以访问 它们自己的 注入器方法有限,因此在模块上使用 @Inject 方法和字段会引入 second 注入器,这可能很快就会变得混乱。

在这种情况下,我会单独为配置创建一个 Injector,然后 create a child injector 使用基于该配置的模块。您的模块应该负责配置绑定,而不是选择要安装的其他模块——这项工作最好留给根应用程序。

如果您觉得必须在模块中保留条件 installation,只需将配置值直接作为构造函数参数并让您的顶级对象(创建您的注入器)提供它需要。这样可以防止两个 Injector 在同一个对象实例中同时处于活动状态,这样一切都更容易理解。

对于类似的问题和解决方案,请参阅此 SO 问题:"Accessing Guice injector in its Module?"

嗯,我建议你看看 Netflix Governator framework。配置如下所示:

LifecycleInjector injector = LifecycleInjector.builder()
          .withModuleClass(MyModule.class)
          .withBootstrapModule(new InitializationModule()).build();

其中 InitializationModule:

public class InitializationModule implements BootstrapModule {

    public void configure() {
      bind(Boolean.class).toInstance(readFromConfig());
    }
}

或者更好的是,您可以使用 Configuration 功能

看起来像这样

 public class MyModule implements Module {
    //read from config.properties
    @Configuration("configs.shouldInstallOtherModule")
    private final Boolean shouldInstallOtherModule;

    public void configure() {
      if(shouldInstallOtherModule) {
       install(SomeOtherModule);       
       }

    }
}