【问题标题】:Using Guice, inject dependency in child class使用Guice,在子类中注入依赖
【发布时间】:2014-07-26 22:08:25
【问题描述】:

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

【问题讨论】:

    标签: java dependency-injection guice


    【解决方案1】:

    当您扩展一个类时,guice 会为您处理父依赖项的注入。 因此,您只需让 Guice 为您创建一个 TrainingCommandData 实例,您就会自动获得 TelemetryServiceClient 注入。

    上述代码存在一些问题:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      相关资源
      最近更新 更多