2012-01-26 31 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());