如何使用 Google Guice 绑定不同的接口?

2023-11-30

我是否需要创建一个新模块,并将接口绑定到不同的实现?

Chef newChef = Guice.createInjector(Stage.DEVELOPMENT, new Module() {
     @Override
      public void configure(Binder binder) {
        binder.bind(FortuneService.class).to(FortuneServiceImpl.class);
      }

    }).getInstance(Chef.class);

Chef newChef2 = Guice.createInjector(Stage.DEVELOPMENT, new Module() {
  @Override
  public void configure(Binder binder) {
    binder.bind(FortuneService.class).to(FortuneServiceImpl2.class);
  }

}).getInstance(Chef.class);

我无法触及厨师课程或界面。我只是一个在运行时将 Chef 的 FortuneService 绑定到不同接口的客户端。


采取看起来像机器人腿部分,在 Guice 常见问题解答中进行了描述。 “如何创建一个具有两个 Leg 对象的机器人,左侧注射了 LeftFoot,右侧注射了 RightFoot。”但只有一个 Leg 类在两种上下文中都被重用。

有一个 PrivateModules 解决方案。它使用两个独立的私有模块,一个 @Left 模块和一个 @Right 模块。每个都有未注释的 Foot.class 和 Leg.class 的绑定,并公开带注释的 Leg.class 的绑定:

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"));
          }
        });
  }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Google Guice 绑定不同的接口? 的相关文章

随机推荐