如何使用Google Guice绑定不同的界面? [英] How do I bind Different Interfaces using Google Guice?

查看:184
本文介绍了如何使用Google Guice绑定不同的界面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Do I need to create a new module with the Interface bound to a different implementation?

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 Class和Interfaces。我只是一个客户端在运行时绑定到Chef的FortuneService到不同的接口。

I cannot touch the Chef Class nor the Interfaces. I am just a client binding to Chef's FortuneService to different Interfaces at runtime.

推荐答案

看起来像机器人腿部部分。 如何创建一个带有两个Leg对象的机器人,左边的一个用LeftFoot注入,另一个用RightFoot注入。但只有一个Leg类在两个上下文中都被重用。

Take looks like the Robot Legs section, described in the Guice FAQ. "How to create a robot with a two Leg objects, the left one injected with a LeftFoot, and the right one with a RightFoot." But only one Leg class that's reused in both contexts.

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

There's a PrivateModules solution. It uses two separate private modules, a @Left one and an @Right one. Each has a binding for the unannotated Foot.class and Leg.class, and exposes a binding for the annotated 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();
}

...并将它们粘合在一起:

...and to glue it all together:

  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"));
          }
        });
  }

这篇关于如何使用Google Guice绑定不同的界面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆