2011-12-02 11 views
14

guiceでは、@ Singletonスコープはシングルトンパターンを参照していません。 「Dhanji」の「依存性注入」の本によると Guice - 複数のインジェクタ/モジュールを使って同じシングルトンインスタンスを共有する方法

は非常に単純に、シングルトンのコンテキストは、インジェクタそのものです。 シングルトンの寿命は、インジェクタの寿命に結びついています(図5.8)。 したがって、 インジェクタごとにシングルトンのインスタンスが1つだけ作成されます。同じアプリケーションに複数のインジェクタが存在する場合は、 が可能であるため、この最後の点を強調することが重要です。このようなシナリオでは、 では、各インジェクタは、単一スコープのオブジェクトの異なるインスタンスを保持します。

Singleton scope

それは、複数のモジュールと複数のインジェクタを通じて同じシングルトンのインスタンスを共有することは可能ですか?

答えて

21

あなたはInjector.createChildInjectorを使用することができます。

// bind shared singletons here 
Injector parent = Guice.createInjector(new MySharedSingletonsModule()); 
// create new injectors that share singletons 
Injector i1 = parent.createChildInjector(new MyModule1(), new MyModule2()); 
Injector i2 = parent.createChildInjector(new MyModule3(), new MyModule4()); 
// now injectors i1 and i2 share all the bindings of parent 
3

あなたがいることを必要とする理由私は表示されませんが、あなたが本当にしたい場合は、それが可能だ:

package stackoverflow; 

import javax.inject.Inject; 
import javax.inject.Singleton; 

import junit.framework.Assert; 

import org.junit.Test; 

import com.google.inject.AbstractModule; 
import com.google.inject.Guice; 
import com.google.inject.Injector; 
import com.google.inject.Module; 

public class InjectorSingletonTest { 

    static class ModuleOne extends AbstractModule { 
     @Override 
     protected void configure() { 
      bind(MySingleton.class); 
     } 
    } 

    static class ModuleTwo extends AbstractModule { 
     final MySingleton singleton; 

     @Inject 
     ModuleTwo(MySingleton singleton){ 
      this.singleton = singleton; 
     } 

     @Override 
     protected void configure() { 
      bind(MySingleton.class).toInstance(singleton); 
     } 
    } 

    @Singleton 
    static class MySingleton { } 

    @Test 
    public void test(){ 
     Injector injectorOne = Guice.createInjector(new ModuleOne()); 

     Module moduleTwo = injectorOne.getInstance(ModuleTwo.class); 
     Injector injectorTwo = Guice.createInjector(moduleTwo); 

     MySingleton singletonFromInjectorOne = 
       injectorOne.getInstance(MySingleton.class); 

     MySingleton singletonFromInjectorTwo = 
       injectorTwo.getInstance(MySingleton.class); 

     Assert.assertSame(singletonFromInjectorOne, singletonFromInjectorTwo); 
    } 
} 
関連する問題