java
public abstract class MyDatabase extends RoomDatabase {
...
}
-
在 Android 开发中,MyDatabase 在子模块中,在主模块中引用子模块并使用 MyDatabase 时,出现如下错误信息
Cannot access androidx. room. RoomDatabase
-
在子模块的 build.gradle 文件中,依赖声明如下
groovy
dependencies {
implementation "androidx.room:room-runtime:2.2.5"
annotationProcessor "androidx.room:room-compiler:2.2.5"
}
问题原因
- 子模块对 Room 的依赖如果使用 implementation 声明,则主模块无法引用到这些依赖,在主模块中访问 Room API 失败
处理策略
- 使用 api 来声明需要传递的依赖
groovy
// 原来是这样的
dependencies {
implementation "androidx.room:room-runtime:2.2.5"
annotationProcessor "androidx.room:room-compiler:2.2.5"
}
groovy
// 修改成这样
dependencies {
api "androidx.room:room-runtime:2.2.5"
annotationProcessor "androidx.room:room-compiler:2.2.5"
}
补充学习
- Gradle 提供了 api 和 implementation 两种常用方式来声明依赖
-
implementation:依赖项仅在当前模块内部可用,不会传递给其他模块
-
api: 依赖项在当前模块内部可用,并且会传递给其他模块