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

相关推荐
淘源码d2 小时前
医学影像云PACS系统——PACS诊断工作站
java·源码·影像处理·医院管理系统·影像工作站·云pacs系统·dicom 标准通信
韩曙亮2 小时前
【Flutter】Flutter 进程保活 ③ ( 屏幕常亮设置 | Flutter 禁止息屏、关闭自动锁屏、屏蔽系统屏保 )
android·flutter·ios·屏幕常亮·禁止息屏
NiceCloud喜云3 小时前
Anthropic 一周三连发:Cowork 多端、Fable 5 按需付费、J-space 论文的技术解读
java·服务器·网络·人工智能·ai
爱笑鱼3 小时前
NDK、SDK、APP、Framework、Native 到底怎么区分?
android
SamDeepThinking3 小时前
组合还是继承?我在项目里主要看这两个判断
java·后端·面试
momo3 小时前
JAVA基础知识
java·开发语言
私人珍藏库3 小时前
[Android] 发票制作器-内置多行业专业模板
android·人工智能·app·软件·多功能
就叫_这个吧4 小时前
Activiti7工作流入门+案例应用
java·activiti7·工作流
Z_W_H_4 小时前
minikube start --driver=docker --memory=4000mb出现PROVIDER_DOCKER_NEWGRP
java·docker·minikube