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

相关推荐
lzhdim11 分钟前
C#不为人知的10个魔法特性:资深开发者也会震惊的底层奥秘
java·前端·javascript·算法·c#
ProcessOn官方账号24 分钟前
java IO操作 你快速认识IO的相关基本知识
java·开发语言
计算机毕设定制辅导-无忧学长34 分钟前
《基于Spring Boot的减脂轻食购物网站》
java·vue.js·spring boot·后端·减脂轻食购物网站
青山木36 分钟前
Hot 100 --- 下一个排列
java·数据结构·算法·leetcode
Thinker QAQ36 分钟前
并发编程(六):Atomic 的实现——从 Runtime 到 CPU
java·go·cas·并发编程·atomic·cpython
沐欣工作室_lvyiyi1 小时前
基于SpringBoot的博物馆预约系统设计与实现(论文+源码)
java·spring boot·后端·计算机毕业设计
只睡四小时1 小时前
JS 手写 D-pad 空间导航:电视端焦点引擎实战
android·开发语言·前端·javascript·ecmascript·hls·空间导航
恋猫de小郭2 小时前
Android 原生的 Compose A2UI 也来了,你还抱着 XML 养老吗?
android·前端·flutter
程序媛_2 小时前
【JMeter】准备token文件
android·jmeter