Appearance
版本目录(Version Catalog)
版本目录(Version Catalog)是 Gradle 7.4+ 推出的现代依赖版本管理方式,通过 TOML 文件集中管理所有依赖版本,提供类型安全的 API。
创建版本目录
在 gradle/libs.versions.toml 文件中定义:
toml
# gradle/libs.versions.toml
[versions]
# 版本号定义
spring-boot = "3.2.0"
spring-cloud = "2023.0.0"
kotlin = "1.9.22"
junit = "5.10.1"
guava = "32.0.1-jre"
jackson = "2.15.3"
lombok = "1.18.30"
mockito = "5.8.0"
[libraries]
# 库定义
spring-boot-web = { module = "org.springframework.boot:spring-boot-starter-web", version.ref = "spring-boot" }
spring-boot-data-jpa = { module = "org.springframework.boot:spring-boot-starter-data-jpa", version.ref = "spring-boot" }
spring-boot-security = { module = "org.springframework.boot:spring-boot-starter-security", version.ref = "spring-boot" }
spring-boot-test = { module = "org.springframework.boot:spring-boot-starter-test", version.ref = "spring-boot" }
spring-boot-bom = { module = "org.springframework.boot:spring-boot-dependencies", version.ref = "spring-boot" }
guava = { module = "com.google.guava:guava", version.ref = "guava" }
jackson-databind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "jackson" }
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" }
junit-launcher = { module = "org.junit.platform:junit-platform-launcher" }
lombok = { module = "org.projectlombok:lombok", version.ref = "lombok" }
mockito = { module = "org.mockito:mockito-core", version.ref = "mockito" }
[bundles]
# 依赖包(一次引入多个相关依赖)
spring-web = ["spring-boot-web", "spring-boot-data-jpa"]
testing = ["junit-jupiter", "mockito"]
[plugins]
# 插件定义
spring-boot = { id = "org.springframework.boot", version.ref = "spring-boot" }
kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }在 build.gradle.kts 中使用
kotlin
plugins {
// 使用版本目录中的插件
alias(libs.plugins.spring.boot)
alias(libs.plugins.kotlin.jvm)
}
dependencies {
// 使用版本目录中的库(IDE 有自动补全!)
implementation(platform(libs.spring.boot.bom))
implementation(libs.spring.boot.web)
implementation(libs.spring.boot.data.jpa)
implementation(libs.guava)
compileOnly(libs.lombok)
annotationProcessor(libs.lombok)
// 使用 bundle(一次引入多个依赖)
testImplementation(libs.bundles.testing)
testRuntimeOnly(libs.junit.launcher)
}版本目录的优势
- 集中管理:所有版本号在一个文件中
- 类型安全:IDE 自动补全,错误在编译时发现
- TOML 格式:比 Groovy/Kotlin DSL 更简洁,非开发者也能理解
- 跨项目共享:可以在
settings.gradle.kts中引入外部版本目录
多版本目录
kotlin
// settings.gradle.kts
dependencyResolutionManagement {
versionCatalogs {
// 默认的 libs 目录(来自 gradle/libs.versions.toml)
// 创建额外的版本目录
create("testLibs") {
from(files("gradle/test-libs.versions.toml"))
}
// 从远程引入版本目录
create("sharedLibs") {
from("com.example:shared-catalog:1.0.0")
}
}
}使用:
kotlin
dependencies {
testImplementation(testLibs.junit.jupiter)
implementation(sharedLibs.company.core)
}版本目录与 Renovate/Dependabot
版本目录文件对自动依赖更新工具非常友好:
yaml
# .github/dependabot.yml
version: 2
updates:
- package-ecosystem: "gradle"
directory: "/"
schedule:
interval: "weekly"Dependabot 会自动识别 libs.versions.toml 并提交升级 PR。