可以使用儿童注射器来完成此操作,但需要进行一些设置。子注入器将防止长期绑定依赖于短期绑定。下面是一个例子:
class ForeverModule extends AbstractModule {
...
}
class TemporaryModule extends AbstractModule {
...
}
class Main {
public static void main(String... args) {
Injector foreverInjector = Guice.createInjector(new ForeverModule());
Injector injector = foreverInjector.createChildInjector(
new TemporaryModule());
/*
* Do stuff with the injector as you would normally. When you
* get bored of that injector, create a replacement injector
* as a child of the long-lived injector.
*/
}
}
永久模块中的单例绑定将持续到该模块存在时为止。只要使用相应的注入器,临时模块中的单例绑定就可以持续。
警告:
默认情况下,将在顶级注入器中创建即时绑定。如果您需要一个短期绑定,那么您需要在子注入器的模块中绑定接口和实现。看起来是这样的:
public void configure() {
bind(Foo.class).to(RealFoo.class);
bind(RealFoo.class);
}