是否有可能为模块注入价值

时间:2015-05-05 11:14:35

标签: java dependency-injection guice

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

 public class MyModule implements Module {

    private final Boolean shouldInstallOtherModule;

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

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

    }
}

2 个答案:

答案 0 :(得分:1)

虽然可以注入模块,或者从注射器获取模块,但是更好的设计决策是:模块可以以有限的方式访问他们自己的注射器,所以模块上的@Inject方法和字段引入了第二个注入器,这可能会很快变得混乱。

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

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

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

答案 1 :(得分:0)

好吧,我建议你看一下 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);       
       }

    }
}
相关问题