小编Joe*_*oel的帖子

Guice:将对象从已安装的模块注入到依赖的已安装模块

我对新 Guice 还很陌生,但到目前为止我已经相当成功了。

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

public class ServerModule extends AbstractModule {

  @Override
  protected void configure() {
    install(new DbModule());
    install(new ModuleA());
    install(new ModuleB());
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

我遇到的问题是其他两个模块依赖DbServiceDbModule. IE 我需要将DbService对象注入到其他两个已安装的模块(ModuleAModuleB)中。

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

install(new DbModule());    
install(new ModuleA(dbService));
install(new ModuleB(dbService)));
Run Code Online (Sandbox Code Playgroud)

我已经尝试过使用提供程序@provider来提供 DbService 实例,但是当我如上所示手动构建模块时,它不会工作。

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

dependency-injection guice

5
推荐指数
1
解决办法
4135
查看次数

标签 统计

dependency-injection ×1

guice ×1