【问题标题】:Does GIN support anything like child injectors?GIN 是否支持儿童注射器之类的东西?
【发布时间】:2012-01-26 09:24:32
【问题描述】:

我有一个包含子应用程序的应用程序。我想隔离 GIN 注入,以便每个子应用程序可以具有相同核心共享类的单独实例。我还希望注入器将一些核心模块的类提供给所有子应用程序,以便可以共享单例实例。例如

GIN Modules:
  Core - shared
  MetadataCache - one per sub-application
  UserProvider - one per sub-application

在 Guice 中,我可以使用 createChildInjector 执行此操作,但在 GIN 中看不到明显的等价物。

我可以在 GIN 中实现类似的东西吗?

【问题讨论】:

    标签: java gwt gwt-gin


    【解决方案1】:

    感谢@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 实例,但在它们的私有注册中具有不同的 Thing 实例:

    System.out.println(injector.getOwner1().toString());
    System.out.println(injector.getOwner2().toString());
    

    【讨论】:

      【解决方案2】:

      这里是 SOF http://code.google.com/p/google-gin/wiki/PrivateModulesDesignDoc。 希望对你有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-11
        • 2021-06-10
        • 2013-08-09
        • 2023-03-14
        • 1970-01-01
        • 2010-10-06
        • 1970-01-01
        相关资源
        最近更新 更多