我对新 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)
我遇到的问题是其他两个模块依赖DbService于DbModule. IE 我需要将DbService对象注入到其他两个已安装的模块(ModuleA和ModuleB)中。
由于ModuleA和ModuleB不是由注入器创建的(我正在构建它们,如上所示),因此我无法将创建的 DbService 实例注入到这些模块中,甚至无法将它们传递给构造函数。IE:
install(new DbModule());
install(new ModuleA(dbService));
install(new ModuleB(dbService)));
Run Code Online (Sandbox Code Playgroud)
我已经尝试过使用提供程序@provider来提供 DbService 实例,但是当我如上所示手动构建模块时,它不会工作。
如果我能让注入器创建ModuleA和ModuleB,我想我就能够将DbService实例注入到它们中,但我不知道该怎么做。 …