我希望在使用guice实例化子类时将依赖注入父类。在下面的示例中,我尝试创建TrainingCommandData
的实例,同时我希望能够在运行时使用Guice注入TelemetryServiceClient
。我怎么能这样做?
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;
}
}
答案 0 :(得分:2)
当你扩展一个类时,guice会为你注入父依赖项。 所以你只需让Guice为你创建一个TrainingCommandData实例,你就会自动注入TelemetryServiceClient。
上述代码存在一些问题: