【发布时间】: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 对象注入另外两个已安装的模块(ModuleA 和ModuleB)。
由于ModuleA 和ModuleB 不是由注入器创建的(我正在构建它们,如上所示),我无法将创建的 DbService 实例注入到这些模块中,甚至无法将它们传递给构造函数。即:
install(new DbModule());
install(new ModuleA(dbService));
install(new ModuleB(dbService)));
我已经尝试过使用提供程序@provider 来提供 DbService 的实例,但是由于我是如上所示手动构建模块,所以它不起作用。
如果我能让注入器创建ModuleA 和ModuleB,我想我就可以将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