2012-01-26 28 views
4

我有一個包含子應用程序的應用程序。我想分離GIN注入,以便每個子應用程序可以具有相同核心共享類的單獨實例。我也希望注入器將一些核心模塊的類提供給所有子應用程序,以便可以共享單例實例。例如GIN支持兒童注射器之類的任何東西嗎?

GIN Modules: 
    Core - shared 
    MetadataCache - one per sub-application 
    UserProvider - one per sub-application 

在吉斯我可以做到這一點使用createChildInjector,但我不能看到GIN一個明顯的等價物。

我可以在GIN中實現類似的功能嗎?

回答

4

我解決了這個要歸功於@Abderrazakk給出的鏈接,但鏈接是不太主動與指示,我想我會在這裏添加一個樣品溶液太:

私人GIN模塊,讓你有單層注入,其中在私有模塊內註冊的類型僅對在該模塊內創建的其他實例可見。所有非私人模塊中註冊的類型仍然可用。

讓我們有一些類型的樣品注入(和注入):

public class Thing { 
    private static int thingCount = 0; 
    private int index; 

    public Thing() { 
     index = thingCount++; 
    } 

    public int getIndex() { 
     return index; 
    } 
} 

public class SharedThing extends Thing { 
} 

public class ThingOwner1 { 
    private Thing thing; 
    private SharedThing shared; 

    @Inject 
    public ThingOwner1(Thing thing, SharedThing shared) { 
     this.thing = thing; 
     this.shared = shared; 
    } 

    @Override 
    public String toString() { 
     return "" + this.thing.getIndex() + ":" + this.shared.getIndex(); 
    } 
} 

public class ThingOwner2 extends ThingOwner1 { 
    @Inject 
    public ThingOwner2(Thing thing, SharedThing shared) { 
     super(thing, shared); 
    } 
} 

像這樣創建兩個專用模塊(使用ThingOwner2用於第二一個):

public class MyPrivateModule1 extends PrivateGinModule { 
    @Override 
    protected void configure() { 
    bind(Thing.class).in(Singleton.class); 
    bind(ThingOwner1.class).in(Singleton.class); 
    } 
} 

和一個共享模塊:

public class MySharedModule extends AbstractGinModule { 
    @Override 
    protected void configure() { 
     bind(SharedThing.class).in(Singleton.class); 
    } 
} 

現在註冊在我們的噴油器兩個模塊:

@GinModules({MyPrivateModule1.class, MyPrivateModule2.class, MySharedModule.class}) 
public interface MyGinjector extends Ginjector { 
    ThingOwner1 getOwner1(); 
    ThingOwner2 getOwner2(); 
} 

最後,我們可以看看,看看這兩個ThingOwner1和ThingOwner2實例具有相同的SharedThing實例從共享模塊,但是從他們的私人註冊不同的事情實例:

System.out.println(injector.getOwner1().toString()); 
System.out.println(injector.getOwner2().toString());