依赖管理 → Version Catalog

依赖管理 → Version Catalog

老写法(Groovy --- 散落各处的版本号)

groovy 复制代码
// app/build.gradle
implementation 'androidx.core:core-ktx:1.12.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.google.code.gson:gson:2.10.1'

// 或者抽到 ext 里
ext {
    retrofitVersion = '2.9.0'
    gsonVersion = '2.10.1'
}
// implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"

问题在哪里

版本号散落在每个 module 的 build.gradle 里,同一个库两个 module 可能用了不同版本。ext 方式没有 IDE 自动补全,只能手动敲,容易敲错。

新写法(Version Catalog)

gradle/libs.versions.toml

toml 复制代码
[versions]
retrofit = "2.9.0"
gson = "2.10.1"
coreKtx = "1.12.0"

[libraries]
retrofit = { module = "com.squareup.retrofit2:retrofit", version.ref = "retrofit" }
gson = { module = "com.google.code.gson:gson", version.ref = "gson" }
coreKtx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" }

使用:

kotlin 复制代码
dependencies {
    implementation(libs.retrofit)
    implementation(libs.gson)
    implementation(libs.coreKtx)
}

一句话注意

Version Catalog 是 Gradle 7.0+ 的原生特性,不需要额外插件。所有依赖和版本集中在 libs.versions.toml 一个文件里,IDE 对 libs.xxx 有完整的代码补全和跳转。多 module 项目下,一个库的版本升级只需要改 TOML 里一个地方。

libs.versions.toml 里可以用 [bundles] 把常用的一组依赖打包:

toml 复制代码
[bundles]
network = ["retrofit", "gson", "okhttp"]

使用时就一行:implementation(libs.bundles.network)


Java Android 老项目迁移系列,持续更新中。

相关推荐
2501_916007474 分钟前
使用Apple Dashboards显示和自定iOS应用性能指标与数据可视化指南
android·ios·小程序·https·uni-app·iphone·webview
霸道流氓气质5 分钟前
Spring AI Alibaba 系列总结:Java 工程师 AI 能力全景图谱
java·人工智能·spring
leluckys13 分钟前
【KMP】-KMP 项目commonMain、androidMain、iosMain 到底放什么?
kotlin
二十雨辰23 分钟前
[Java]-场景题
java·开发语言
MZA66627 分钟前
Spring Boot 实战:基于自定义注解 + AOP 实现 Kafka 消息无侵入异步上送
java·spring boot·kafka
我是大猴子28 分钟前
为什么SSE无法代替Webscoket
java
重庆小透明33 分钟前
Kafka 完全指南:从基础组件到核心原理(包含面试题)
java·分布式·微服务·架构·kafka
蜡台37 分钟前
# 已解决|MySQL 8\.4\.11 密码正确仍报错1045 \(28000\) Access denied 终极修复方案
android·mysql·adb
JMchen12342 分钟前
2026年六款主流AI编程工具深度实测:Cursor、Copilot、Claude Code等对比与选型思考
android·kotlin·copilot·ai编程·开发工具·cursor·claude code
CodeStats44 分钟前
【Java文件IO】Java 文件 IO 体系深度拆解(中):NIO API 详解、Files 与 FileChannel 巅峰对决
java·io·文件·nio·零拷贝·mmap