题
我有一个包含子应用程序的应用程序。我想分离杜松子酒注入,使每个子应用程序可以具有相同核心共享类的单独实例。我还希望喷射器从某些核心模块向所有子应用程序提供类,以便可以共享单例实例。例如。
GIN Modules:
Core - shared
MetadataCache - one per sub-application
UserProvider - one per sub-application
.
在guice中,我可以使用createChildInjector
来做这个,但我看不到杜松子酒中的明显等效物。
我可以在杜松子酒中获得类似的东西吗?
解决方案
在这里,它位于sof http://code.google.com/p/ google-gin / wiki / privatemodlesdesigndoc 。 希望它对你有帮助。
其他提示
我已经解决了这一点,感谢@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);
}
}
创建这样的两个私有模块(使用它的东西2为第二个):
.
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();
}
最后我们可以查看并看一下,任何东西都有来自共享模块的相同的SharEdthing实例,但来自其私有注册的不同事项:
.System.out.println(injector.getOwner1().toString());
System.out.println(injector.getOwner2().toString());