簡體   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