我解決了這個要歸功於@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());