依赖管理 → 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 老项目迁移系列,持续更新中。

相关推荐
Irene199112 分钟前
Flink 学习日志 01:前端转大数据的实战避坑指南
java·jvm·flink
Thomas.Sir13 分钟前
第1课:SpringBoot 4.x 快速上手:新特性、环境准备与第一个HelloWorld程序
java·spring boot
小铁-Android25 分钟前
CompletableDeferred:Kotlin 协程中用于一次性挂起通信的工具
android·kotlin
恋猫de小郭27 分钟前
Flutter 的文字为什么比 SwiftUI 更细?问题主要在 Skia 的 256 项查找表里
android·前端·flutter
ii_best31 分钟前
安卓手机开发、iOS 手机开发都能用:按键精灵远程调试,设备在千里外也能改脚本
android·ios·智能手机·自动化·按键精灵
devilnumber33 分钟前
Java 内部迭代 vs 外部迭代:从原理到实战避坑
java·开发语言
杨运交38 分钟前
080-缓存模块-Spring Cache缓存键前缀设计与租户隔离实践
java·spring·缓存
\光辉岁月/42 分钟前
5.math类
java·开发语言
文丑颜不良啊44 分钟前
LeetCode76~100题目解析
java·leetcode
她的男孩1 小时前
页面已发布用户仍进不去:Forge Admin 门户入口与系统菜单挂载解耦
java·spring boot·低代码