这里有一些奇怪的事情。假设您有一个这样的模块:
public class ParentModule extends AbstractModule {
@Override
public void configure() {
bindConstant().annotatedWith(Names.named("key")).to("key");
}
}
然后我们还有这样的东西:
public class DependentModule extends AbstractModule {
private final String key;
@Inject public DependentModule(@Named("key") String key) { this.key = key; }
@Override
public void configure() {
// Configure bindings that make use of key...
}
}
Injector parent = Guice.createInjector(new ParentModule());
Injector child = parent.createChildInjector(parent.getInstance(DependentModule.class));
// Now just ignore parent and work with child exclusively
这看起来非常麻烦,但在某些情况下可能是必要和有用的(例如,如果键是更复杂的数据类型)。无论如何,有没有办法重构此代码,以便 ParentModule
绑定(bind) key ,使用 key 创建 DependentModule
,并安装创建的 DependentModule
?也就是说,消费者可以简单地使用单个注入(inject)器,而不必执行这个两个注入(inject)器的技巧?
最佳答案
不可能注入(inject)一些东西然后安装它。注入(inject)仅在所有 configure()
方法运行后发生,此时为时已晚。但你可以这样做:
public class MyModule extends AbstractModule {
@Override
public void configure() {
bindConstant().annotatedWith(Names.named("key")).to("key");
}
@Provides
Dependency provideDependency(@Named("key") String key) {
// Use key here
}
}
关于java - Guice:注入(inject)模块然后安装它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27515476/