How do I bind Different Interfaces using Google Guice?

后端 未结 3 946
臣服心动
臣服心动 2021-01-14 01:02

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

Chef newChef = Guice.createInjector(Stage.DEVELOPMENT, new Module()          


        
3条回答
  •  感动是毒
    2021-01-14 01:29

    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.

    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 annotation;
    
      LegModule(Class 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"));
              }
            });
      }
    

提交回复
热议问题