推荐使用 libs.versions.toml 管理依赖,它将版本号与坐标分离,集中维护、ide 支持跳转补全、保障多模块版本一致,需 agp 8.0+ 和 gradle 8.0+。

直接在 dependencies 块里写 implementation 就能加,但不同方式影响项目可维护性、多模块一致性、IDE 支持程度——选错方式,后期改起来很疼。
用 implementation 直接写坐标最简单,但只适合单模块小项目
这是新手最常写的写法,比如在 app/build.gradle 里:
dependencies {
implementation 'androidx.core:core-ktx:1.12.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
}
它能立刻生效,同步后自动下载。但问题也很直接:
- 版本号散落在各处,升级一个库得全局搜
retrofit手动改 - 多个 module(如
feature-login、data)用同一库不同版本时,Gradle 会静默取高版本,可能引发运行时行为不一致 - IDE 不会帮你校验版本冲突,直到编译或运行时报
ClassCastException或NoClassDefFoundError
用 libs.versions.toml 管理依赖(Android Studio 推荐方式)
这是当前新项目默认启用的方式,路径固定为 gradle/libs.versions.toml。它把版本号和坐标分离,让 IDE 能联动提示、跳转、校验。
示例内容:
[versions]
retrofit = "2.9.0"
okhttp = "4.12.0"
[libraries]
retrofit-core = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
okhttp-logging = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "okhttp" }
[plugins]
android-application = { id = "com.android.application", version = "8.3.0" }
然后在 app/build.gradle 中引用:
dependencies {
implementation libs.retrofit.core
implementation libs.okhttp.logging
}
好处明显:
- 所有版本集中在一处,改
[versions]就全项目生效 - IDE 支持 Ctrl+Click 跳转到定义,补全时自动带
libs.前缀 - 如果某库被多个 module 使用,只要都用
libs.xxx,版本天然统一
注意:必须搭配 Android Gradle Plugin 8.0+ 和 Gradle 8.0+,老项目迁移需检查 gradle/wrapper/gradle-wrapper.properties 里的 distributionUrl。
用 buildSrc 写 Kotlin 对象管理依赖(适合中大型多模块项目)
当 libs.versions.toml 不够用——比如需要动态拼接版本("${Versions.kotlin}-ksp")、做条件判断、或复用已有 Kotlin 工具类时,buildSrc 是更灵活的选择。
结构如下:
buildSrc/
├── build.gradle.kts
└── src/main/kotlin/
└── Dependencies.kt
Dependencies.kt 示例:
object Versions {
const val kotlin = "1.9.20"
const val retrofit = "2.9.0"
}
object Libs {
const val retrofit = "com.squareup.retrofit2:retrofit:${Versions.retrofit}"
const val kotlinStdlib = "org.jetbrains.kotlin:kotlin-stdlib:${Versions.kotlin}"
}
然后在 app/build.gradle 中使用:
dependencies {
implementation(Libs.retrofit)
implementation(Libs.kotlinStdlib)
}
关键点:
-
buildSrc是纯 Kotlin/Java 代码,可单元测试、可复用逻辑、支持类型安全 - 修改后需重新构建
buildSrc(通常改完保存,AS 会自动触发),否则新依赖不生效 - 不能在
buildSrc里读取gradle.properties,变量必须硬编码或通过System.getenv()注入
真正容易被忽略的不是“怎么写”,而是“谁来管版本决策”。哪怕用了 libs.versions.toml,如果团队没约定好升级流程(比如安全漏洞必须 48 小时内合入),或者没定期 ./gradlew app:dependencies | grep retrofit 检查实际解析版本,统一管理就只是个架子。











