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

相关推荐
aiotto资源分享20 分钟前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
RuoyiOffice1 小时前
SpringBoot3+Vue3 采购到付款:ERP、WMS与财务如何按同一来源协同
java·spring boot·架构·vue
GY-931 小时前
【Android】数据分层和依赖注入
android
文丑颜不良啊1 小时前
LeetCode3261~3280题目解析
java·leetcode
代码不停1 小时前
Spring 原理
java·spring
企业数字化笔记2 小时前
报表上线怎么对账?口径回归、权限抽检与差异定位
java·spring boot·mysql
乌暮2 小时前
少写重复 CRUD:用大白话搞懂 MyBatis-Plus
java·开发语言·spring boot·面试·mybatis
传奇开心果编程2 小时前
【Jetpack Compose娓娓道来】第44课:持久化——让数据“关掉App也不丢”
android·kotlin·移动开发·数据持久化·jetpack compose·ui框架·声明式ui
CoderYanger2 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第四弹):图书管理系统(用户登录+添加图书)
java·数据库·spring boot·mysql·面试·java-ee·mybatis
goyeer2 小时前
【Kubernetes】Kubernetes之CRI详解
java·容器·kubernetes