[英]Using Guice, inject dependency in child class
I want to inject dependency into a parent class while instantiating the child class using guice. 我想在使用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. 在下面的示例中,我希望创建一个TrainingCommandData
实例,同时希望能够在运行时使用Guice注入TelemetryServiceClient
。 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. 当您扩展类时,guice将为您处理父依赖项的注入。 So you just let Guice create an instance of TrainingCommandData for you and you automatically get the TelemetryServiceClient injected. 因此,您只需让Guice为您创建TrainingCommandData的实例,即可自动注入TelemetryServiceClient。
There are some problems with the above code though: 上面的代码有一些问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.