java - 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
解决方案
要了解 AutoAnnotation 和 Dagger 2 的工作原理,首先我需要了解 AutoValue
AutoValue 示例:错误:找不到符号类 AutoValue_Animal
然后跟随 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中做了一个示例代码
推荐阅读
- java - 如何在 android studio 中创建指针 UI?
- python - Python:嵌套for循环在第二个循环中失败
- c# - 事件发布和订阅如何在 ON DEMAND 环境中工作
- webpack - 为什么使用 Webpack 4 在生产模式下只生成供应商 css?
- android - Nativescript(Windows):tns平台添加android挂起尝试提取fsevents包
- javascript - React setState 仅将最后一项推送到数组
- powershell - get-childitem 在将文件提取到最后一级时是否锁定文件夹
- sql-server - 数据库的部分克隆
- keras - Keras 损失常数
- networking - 如何通过基于用户 ID 的 Wi-Fi 网络共享文件夹?