在 gradle/libs.versions.toml 中定义 bundle 并在子项目中引用?
解读
这是国内 Android/微服务项目面试里“依赖管理”环节的高频追问。
面试官想确认三件事:
- 你是否真的用过 Version Catalogs(libs.versions.toml) 而不是传统 ext/gradle.buildScript;
- 能否把“bundle”这一语法糖与“子项目”的 classpath 正确关联;
- 是否理解 bundle 的可见域规则(只能在 dependencies 块里解析,不能出现在 buildscript 或 plugin 管理域)。
答错任意一点,都会被追问“那如果子项目里还要额外加单个组件怎么办”“CI 里缓存 key 怎么设计”等连环炮。
知识点
- TOML 文件必须放在根项目 gradle 目录下,文件名固定为 libs.versions.toml,Gradle 7.0+ 自动识别。
- bundle 本质是把一组 alias 打包成 List<Provider<MinimalExternalModuleDependency>>,解析时机与单个 alias 完全一致。
- 子项目引用时,id 与 bundle 名必须与 TOML 中完全一致,区分大小写;Kotlin DSL 用
implementation(libs.bundles.xxx),Groovy DSL 可省略括号。 - bundle 不支持在 buildscript 依赖块里展开,若子项目需要 classpath 级依赖,仍需单独写
classpath(libs.xxx)。 - 子项目若想覆盖版本,可在自身
dependencyConstraints里强制约束,但不能在 TOML 里用 bundle 语法覆盖。 - 国内镜像场景(阿里云、腾讯云)下,Gradle 7.4+ 对 TOML 的缓存 key 会包含文件哈希,修改 bundle 内容不会使远程构建缓存失效,但新增 alias 会;面试时可主动提及“bundle 变动不会导致 cache-miss”体现性能意识。
答案
- 在根项目
gradle/libs.versions.toml中声明
[versions]
retrofit = "2.9.0"
okhttp = "4.10.0"
[libraries]
retrofit-core = { module = "com.squareup.retrofit2:retrofit", version.ref = "retrofit" }
okhttp-core = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }
[bundles]
network = ["retrofit-core", "okhttp-core"]
- 根项目
settings.gradle.kts启用 catalog
dependencyResolutionManagement {
versionCatalogs {
create("libs") {
from(files("gradle/libs.versions.toml"))
}
}
}
- 子项目
feature-login/build.gradle.kts引用
plugins {
id("com.android.library")
}
dependencies {
implementation(libs.bundles.network) // 一行引入 retrofit + okhttp
// 若还需额外加单个库,可继续写:
implementation(libs.okhttp.core)
}
- 若子项目想排除 bundle 中的某个库,需显式 exclude,不能在 bundle 声明层面排除:
implementation(libs.bundles.network) {
exclude(group = "com.squareup.okhttp3", module = "okhttp")
}
- 验证:
./gradlew :feature-login:dependencies --configuration releaseRuntimeClasspath | grep -E "(retrofit|okhttp)"
能看到两条依赖即证明 bundle 生效。
拓展思考
- 多 repo 场景:国内很多公司把基础库放在私有 Maven 仓库,TOML 里可以把 version 抽成占位符,通过 CI 的
ORG_GRADLE_PROJECT_xxx环境变量注入,实现“同一 bundle,不同环境版本”。 - 复合 bundle:可以在 TOML 里再定义一个
bundles.all = ["network", "coroutines"],bundle 之间可以相互引用,但注意循环引用会报CircularDependencyException。 - buildSrc 与 bundle 的取舍:如果子项目还需要在
buildSrc里使用这些库,必须在buildSrc/settings.gradle.kts里再声明一份versionCatalogs,因为buildSrc是独立构建,**不能直接访问主项目的 libs`。 - 性能调优:bundle 展开后依赖数量多,国内大型工程建议打开
org.gradle.parallel=true与configuration-cache=true,并在 CI 里把~/.gradle/caches/version-catalogs目录缓存,减少 TOML 解析耗时。