简体   繁体   English

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

[英]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: 上面的代码有一些问题:

  1. you need to put "@Inject" on your non-default constructor ... and of course guice must be able to create all parameters for you. 您需要在非默认构造函数上放置“ @Inject” ...当然,guice必须能够为您创建所有参数。 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? 在您的用例中,使用setter注入不是一个好选择……为什么您的commanddata建议可以在运行时设置服务的新实例? I would not provide setters but use field injection, or, if you dont like that, constructor injection. 我不提供设置器,而是使用字段注入,或者,如果您不喜欢,则使用构造函数注入。

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

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