首页 > 解决方案 > Dagger 2 多绑定教程的 @AutoAnnotation 不起作用。如何让它工作?

问题描述

在参考https://dagger.dev/multibindings.html,有一段在谈论@AutoAnnotation

class MyComponentTest {
  @Test void testMyComponent() {
    MyComponent myComponent = DaggerMyComponent.create();
    assertThat(myComponent.myKeyStringMap()
        .get(createMyKey("abc", Abc.class, new int[] {1, 5, 10}))
        .isEqualTo("foo");
  }

  @AutoAnnotation
  static MyKey createMyKey(String name, Class<?> implementingClass, int[] thresholds) {
    return new AutoAnnotation_MyComponentTest_createMyKey(name, implementingClass, thresholds);
  }
}

不知何故,我从来没有让它工作。

我要添加以下内容

    implementation 'com.google.auto.value:auto-value:1.5.2'
    annotationProcessor 'com.google.auto.value:auto-value:1.5.2'

并且还添加

    android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true

标签: javaandroidannotationsdagger-2

解决方案


要了解 AutoAnnotation 和 Dagger 2 的工作原理,首先我需要了解 AutoValue

AutoValue 示例:错误:找不到符号类 AutoValue_Animal

然后跟随 AutoAnnotation

@AutoAnnotation 有什么用?怎么可能使用?

之后,我可以使用 AutoAnnotation 探索上面的 Dagger 2 示例。

简而言之,AutoAnnotation 是一个 Java 代码生成器库,可以生成可用于多绑定工作的值等价的 Annotation Key(因为 Java 类不像 Kotlin 数据类,因此需要这样的工具来使其值等价更容易)。

Google 的 AutoValue 文档给出的示例并不是开箱即用的。需要进行一些修改,例如 1. 必须公开 MyComponentTest 以及函数。2. AutoAnnotation 代码不应在 test 文件夹中,而应在实际源文件夹中。3. 为了让 AutoAnnotation 与 Dagger 2 一起工作,我们需要以下设置

android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true

我在https://github.com/elye/demo_android_dagger_autoannotation中做了一个示例代码


推荐阅读