How to @Inject into existing object hierarchy using Guice?

前端 未结 2 1639
萌比男神i
萌比男神i 2021-02-02 17:41

I have an existing object hierarchy where some objects have fields that need to be injected. Also there are some other objects that are constructed using Google Guice and need t

2条回答
  •  旧巷少年郎
    2021-02-02 18:31

    You could inject MembersInjectors to inject nested fields. For example, this will deeply inject an existing Car instance:

    public class Car {
      Radio radio;
      List seats;
      Engine engine;
    
      public Car(...) {...}
    
      @Inject void inject(RadioStation radioStation,
          MembersInjector seatInjector,
          MembersInjector engineInjector) {
        this.radio.setStation(radioStation);
        for (Seat seat : seats) {
          seatInjector.injectMembers(seat);
        }
        engineInjector.injectMembers(engine);
      }
    }
    
    public class Engine {
      SparkPlug sparkPlug;
      Turbo turbo
    
      public Engine(...) {...}
    
      @Inject void inject(SparkPlug sparkplug,
          MembersInjector turboInjector) {
        this.sparkPlug = sparkPlug;
        turboInjector.injectMembers(turbo);
      }
    }
    

提交回复
热议问题