可以使用子注射器来完成此操作,但需要一些设置。子注射器将防止长期绑定依赖于短期绑定。这是一个例子:
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.
*/
}
}
只要该模块存在,forever 模块中的单例绑定就会持续存在。只要您使用相应的注入器,临时模块中的单例绑定就会持续存在。
警告:默认情况下,将在顶级注入器中创建即时绑定。如果您需要短期绑定,则需要在子注入器模块中绑定接口和实现。看起来像这样:
public void configure() {
bind(Foo.class).to(RealFoo.class);
bind(RealFoo.class);
}