簡體   English   中英

Dagger 與 Guice 中的運行時值注入

[英]Runtime value injection in Dagger vs. Guice

我正在將一個項目從 Guice 遷移到 Dagger,並且我試圖了解如何在運行時注入值。 假設我有一個帶有以下配置方法的 Guice 模塊:

  void configure() {
    install(new FactoryModuleBuilder()
        .build(InterfaceXFactory.class));
  }

工廠界面,

public interface InterfaceXFactory{

  ClassX getClassX(
      @Assisted("a") String a,
      @Assisted("b") Integer b);

}

最后:

  ClassX(
      final @Assisted("a") String a,
      final @Assisted("b") Integer b) {
    /.../
  }

這種配置的匕首等價物是什么? 根據我的發現,我可以使用 AutoFactory,但我對 API 的理解不夠好,而且我不知道在 Dagger 中會是什么樣子。 也許這也不是最好的方法。

這個示例將如何轉換為 Dagger,以便我可以獲得與 Guice 實現相同的功能? 我真的很感激幫助!

Dagger 在 2.31 版本中添加了自己的輔助注入,所以沒有太大的改變。

工廠接口需要用@AssistedFactory注解:

@AssistedFactory
public interface InterfaceXFactory{

  ClassX getClassX(
      @Assisted("a") String a,
      @Assisted("b") Integer b);

}

構造函數需要用@AssistedInject注釋:

  @AssistedInject
  ClassX(
      final @Assisted("a") String a,
      final @Assisted("b") Integer b) {
    /*...*/
  }

無需向模塊添加任何內容; Dagger 會自行找到InterfaceXFactory

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM