使用Guice为可重用组件注入不同的实例

时间:2017-03-23 16:27:04

标签: java dependency-injection guice implementation

我是新手做依赖注入,我试图用Google Guice解决以下问题:

在Web应用程序中,我有一些标签需要多次重复使用,但每次都有不同的UI组件和模型依赖项。像这里的代码:

<div class="container">
  <div class="block-top">A</div>
  <div class="block-top">B</div>
  <div class="block-bottom">C</div>
</div>

如何将FooModel和FooComponent注入fooTab 和BarModel和BarCompoment进入barTab?

我已经阅读了很多关于Google Guice中可用的不同技术的内容,但是没有一个适合这个问题,对于我天真的眼睛来说,应该是一个简单的问题。我试图给fooTab和barTab绑定注释但它们只有在我注入选项卡而不是选项卡的依赖项时才会起作用。什么是解决这个问题最方便的方法?

1 个答案:

答案 0 :(得分:3)

这听起来像普通的机器人腿&#34;问题对我来说......这在FAQ中有所涉及,可以通过使用私有模块来解决:

class LegModule extends PrivateModule {
  private final Class<? extends Annotation> annotation;

  LegModule(Class<? extends Annotation> annotation) {
    this.annotation = annotation;
  }

  @Override 
  protected void configure() {
    bind(Leg.class).annotatedWith(annotation).to(Leg.class);
    expose(Leg.class).annotatedWith(annotation);

    bindFoot();
  }

  abstract void bindFoot();
}

public static void main(String[] args) {
  Injector injector = Guice.createInjector(
    new LegModule(Left.class) {
      @Override void bindFoot() {
        bind(Foot.class).toInstance(new Foot("leftie"));
      }
    },
    new LegModule(Right.class) {
      @Override void bindFoot() {
        bind(Foot.class).toInstance(new Foot("righty"));
      }
    });
}
相关问题