Darth.Vader
Darth.Vader

Reputation: 6301

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

Upvotes: 1

Views: 1684

Answers (1)

Jan Galinski
Jan Galinski

Reputation: 12013

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.

Upvotes: 2

Related Questions