我解决了这个要归功于@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());