Dagger 2 多绑定教程的 @AutoAnnotation 不起作用。如何让它工作?

@AutoAnnotation for Dagger 2 Multibinding Tutorial not working. How to get it working?

在提到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);
  }
}

不知怎么的,我从来没有让它工作过。

我要向 gradle 添加以下内容

    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

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

然后是AutoAnnotation

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

简而言之,AutoAnnotation 是一个 Java 代码生成器库,它生成可用于多重绑定工作的值等效注释密钥(因为 Java 类 不像Kotlin Data Class,因此需要这样的工具来使其价值等价更容易)。

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

android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true

我在https://github.com/elye/demo_android_dagger_autoannotation

中制作了示例代码