Guice with parents

前端 未结 3 633
礼貌的吻别
礼貌的吻别 2021-01-11 18:59

What do I do with Guice when I need to call a parent constructor that is also injectable? e.g. I have an abstract parent class that has a constructor that is injected with a

3条回答
  •  粉色の甜心
    2021-01-11 19:10

    A better alternative is to use something similar to the strategy pattern to encapsulate all the fields the superclass wants to inject, and then the subclass can inject that. For example:

    public abstract class Animal {
      /**
       * All injectable fields of the Animal class, collected together
       * for convenience.
       */
      protected static final class AnimalFields {
        @Inject private Foo foo;
        @Inject private Bar bar;
      }
    
      private final AnimalFields fields;
    
      /** Protected constructor, invoked by subclasses. */
      protected Animal(AnimalFields fields) {
        this.fields = fields;
      }
    
      public Foo getFoo() {
        // Within Animal, we just use fields of the AnimalFields class directly
        // rather than having those fields as local fields of Animal.
        return fields.foo;
      }
    
      public Bar getBar() {
        return fields.bar;
      }
    }
    
    public final class Cat extends Animal {
      private final Whiskers whiskers;
    
      // Cat's constructor needs to inject AnimalFields to pass to its superclass,
      // but it can also inject whatever additional things it needs.
      @Inject
      Cat(AnimalFields fields, Whiskers whiskers) {
        super(fields);
        this.whiskers = whiskers;
      }
    
      ...
    }
    

提交回复
热议问题