简体   繁体   中英

Using Guice, inject dependency in child class

I want to inject dependency into a parent class while instantiating the child class using guice. In the example below, I am trying to create an instance of TrainingCommandData while I want to be able to inject TelemetryServiceClient during runtime using Guice. How can I do this?

public class TrainingCommandData extends CommandData {

    private Intent intent;

    public TrainingCommandData(UserCommandResource userCommandResource, Intent intent) {
        super(userCommandResource);
        this.intent = intent;
    }
}

public class CommandData {

    private TelemetryServiceClient telemetryServiceClient;
    private UserCommandResource userCommandResource;

    @Inject
    public void setTelemetryServiceClient(TelemetryServiceClient telemetryServiceClient) {
        this.telemetryServiceClient = telemetryServiceClient;
    }

    public CommandData(UserCommandResource userCommandResource) {
        this.userCommandResource = userCommandResource;
    }
}

When you extend a class, guice will take care of the injection of parent dependencies for you. So you just let Guice create an instance of TrainingCommandData for you and you automatically get the TelemetryServiceClient injected.

There are some problems with the above code though:

  1. you need to put "@Inject" on your non-default constructor ... and of course guice must be able to create all parameters for you. If you only now these parameters at runtime, have a look at the assisted injection extension
  2. Using setter injection is not a good choice in your use case ... why should your commanddata suggest that it is possible to set a new instance of the service at runtime? I would not provide setters but use field injection, or, if you dont like that, constructor injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM