チャイルドインジェクターを使用してこれを実現できますが、いくつかの設定が必要です。チャイルドインジェクターは、長寿命のバインディングが短寿命のバインディングに依存するのを防ぎます。次に例を示します。
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);
}