ChildInjector
ChildInjectorは、任意のInjectorから、そのInjectorが持つモジュールの内容を継承する子Injectorを作成する機能です。
- 子Injectorでは親のコンポーネントが参照でき、インスタンスを取得したり、Injectしたりできます。
- 子Injector作成時にはModuleを渡すことができるので、「親のモジュール+子のモジュール」が子で使えることになります。
- 子で親のモジュールを使うことは可能ですが、逆(親で子のモジュールを使う)は不可です。
// 親Injector Injector parent = Guice.createInjector( new AbstractModule(){ protected void configure() { binder().bind( String.class ).toInstance( "mii" ); } }); // 子Injector Injector child = parent.createChildInjector( new AbstractModule(){ protected void configure() { binder().bind( Integer.class ).toInstance( 100 ); binder().bind( Foo.class ); } }); // 子では、「親+子」のコンポーネントを利用可能 System.out.println( child.getInstance( String.class ) ); System.out.println( child.getInstance( Integer.class ) ); // Injectもできる。 Foo foo = child.getInstance( Foo.class ); System.out.println( foo.str ); System.out.println( foo.i ); .... // Fooの実装 static class Foo { @Inject String str; @Inject Integer i; }
実行結果です。
mii 100 mii 100
親から子のコンポーネントは参照できないので、以下はエラーになります。
// 親Injector Injector parent = Guice.createInjector( new AbstractModule(){ protected void configure() { binder().bind( String.class ).toInstance( "mii" ); binder().bind( Foo.class ); } }); // 子Injector Injector child = parent.createChildInjector( new AbstractModule(){ protected void configure() { binder().bind( Integer.class ).toInstance( 100 ); } });
実行結果です。
Exception in thread "main" com.google.inject.CreationException: Guice creation errors: ....