繁体   English   中英

使用Guice,在子类中注入依赖项

[英]Using Guice, inject dependency in child class

我想在使用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;
    }
}

当您扩展类时,guice将为您处理父依赖项的注入。 因此,您只需让Guice为您创建TrainingCommandData的实例,即可自动注入TelemetryServiceClient。

上面的代码有一些问题:

  1. 您需要在非默认构造函数上放置“ @Inject” ...当然,guice必须能够为您创建所有参数。 如果现在仅在运行时这些参数,请查看辅助注射扩展
  2. 在您的用例中,使用setter注入不是一个好选择……为什么您的commanddata建议可以在运行时设置服务的新实例? 我不提供设置器,而是使用字段注入,或者,如果您不喜欢,则使用构造函数注入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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