【问题标题】:Runtime value injection in Dagger vs. GuiceDagger 与 Guice 中的运行时值注入
【发布时间】:2021-06-01 17:43:47
【问题描述】:

我正在将一个项目从 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 实现相同的功能?非常感谢您的帮助!

【问题讨论】:

    标签: java dependency-injection guice dagger-2


    【解决方案1】:

    Dagger 在 2.31 版本中添加了自己的 assisted injection,因此没有太大变化。

    工厂接口需要注解@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

    【讨论】:

    • 所以你的意思是我们可以完全取消模块中的 install(...).build ,或者它会被其他东西取代?因为我们仍然必须将值传递给组件,对吗? dagger api 显示如下内容: serviceFactory.create(config);看起来对吗?
    • InterfaceXFactory 将自动可用于知道如何注入 ClassX 的每个非辅助构造函数参数的任何组件或子组件(如果适用,则与 InterfaceXFactory 具有相同的范围)。为了获得ClassX 实例,您需要将字符串a 和整数b 传递给InterfaceXFactory;我想 Guice 的工作方式是一样的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2011-01-02
    • 2021-03-04
    相关资源
    最近更新 更多