我有一个包含子应用程序的应用程序。我想隔离 GIN 注入(inject),以便每个子应用程序都可以有相同核心共享类的单独实例。我还希望注入(inject)器将一些核心模块的类提供给所有子应用程序,以便可以共享单例实例。例如
GIN Modules:
Core - shared
MetadataCache - one per sub-application
UserProvider - one per sub-application
在 Guice 中,我可以使用 createChildInjector
执行此操作,但我在 GIN 中看不到明显的等效项。
我可以在 GIN 中实现类似的东西吗?
最佳答案
感谢@Abderrazakk 提供的链接,我解决了这个问题,但由于链接不是很方便,我想我也会在这里添加一个示例解决方案:
私有(private) GIN 模块允许您拥有单层层次注入(inject),其中在私有(private)模块内注册的类型仅对该模块内创建的其他实例可见。在任何非私有(private)模块中注册的类型仍然可供所有人使用。
示例
让我们有一些样本类型要注入(inject)(并注入(inject)):
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);
}
}
像这样创建两个私有(private)模块(第二个使用 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);
}
}
现在在我们的注入(inject)器中注册这两个模块:
@GinModules({MyPrivateModule1.class, MyPrivateModule2.class, MySharedModule.class})
public interface MyGinjector extends Ginjector {
ThingOwner1 getOwner1();
ThingOwner2 getOwner2();
}
最后我们可以查看并看到 ThingOwner1 和 ThingOwner2 实例都具有来自共享模块的相同 SharedThing 实例,但来自其私有(private)注册的不同 Thing 实例:
System.out.println(injector.getOwner1().toString());
System.out.println(injector.getOwner2().toString());
关于java - GIN 是否支持 child 注入(inject)器之类的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9016009/