【问题标题】:Guice: Injecting an object from an installed module to a dependent installed moduleGuice:将对象从已安装的模块注入到依赖的已安装模块
【发布时间】:2013-12-01 00:24:43
【问题描述】:

我对新 Guice 还很陌生,但在此之前我已经相当成功了。

我有一个“主要”Guice 模块 (ServerModule),如下所示,它安装了几个其他模块:

public class ServerModule extends AbstractModule {

  @Override
  protected void configure() {
    install(new DbModule());
    install(new ModuleA());
    install(new ModuleB());
  }
}

第一个安装的模块(DbModule)如下:

public class DbModule extends AbstractModule {
  @Override
  protected void configure() {
    bind(DbService.class).to(DbServiceImpl.class).asEagerSingleton();
  }
}

我遇到的问题是其他两个模块依赖于由DbModule 创建的DbService 实例。 IE。我需要将DbService 对象注入另外两个已安装的模块(ModuleAModuleB)。

由于ModuleAModuleB 不是由注入器创建的(我正在构建它们,如上所示),我无法将创建的 DbService 实例注入到这些模块中,甚至无法将它们传递给构造函数。即:

install(new DbModule());    
install(new ModuleA(dbService));
install(new ModuleB(dbService)));

我已经尝试过使用提供程序@provider 来提供 DbService 的实例,但是由于我是如上所示手动构建模块,所以它不起作用。

如果我能让注入器创建ModuleAModuleB,我想我就可以将DbService 实例注入它们,但我不知道该怎么做。

有没有人知道我怎样才能最好地做到这一点?

编辑:我忘了提到@provider 似乎没用的原因是因为我需要在 ModuleA 本身中使用 DbService,而不是在它的绑定之一中:

public class ModuleA extends AbstractModule {
  @Inject
  private DbService dbService;

  @Override
  protected void configure() {
    if( dbService.getX() )
      bind(Y.class);
  }
}

【问题讨论】:

    标签: dependency-injection guice


    【解决方案1】:

    您不能也不应该这样做,因为 Guice 模块不应该以这种方式使用。

    基本上,Guice 鼓励将配置与实际对象创建分开。除非您创建一个注入器,使用它来创建新模块,然后使用这些模块创建另一个注入器,否则您根本无法注入模块。

    事实上这非常好。你的模块通常不应该有复杂的逻辑,毕竟它只是一个配置。您应该重构您的程序,例如,使用@Provides-methods 或成熟的Providers。然后你将拥有更清晰的依赖配置逻辑。

    【讨论】:

      【解决方案2】:

      你不能这样做。

      在创建 Injector 时会调用 Module.configure() 方法,只有在 Injector 准备好使用后才能进行注入。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-24
        • 1970-01-01
        • 2020-07-05
        • 1970-01-01
        • 2011-09-07
        • 2017-03-13
        相关资源
        最近更新 更多