Skip to content

统一版本管理

在多项目构建中,统一管理依赖版本避免各子项目使用不同版本带来的问题。

方式一:版本目录(推荐)

toml
# gradle/libs.versions.toml
[versions]
spring-boot = "3.2.0"
junit = "5.10.1"

[libraries]
spring-boot-web = { module = "org.springframework.boot:spring-boot-starter-web", version.ref = "spring-boot" }
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" }
kotlin
// 所有子项目使用版本目录
dependencies {
    implementation(libs.spring.boot.web)
    testImplementation(libs.junit.jupiter)
}

方式二:根项目 extra 属性

kotlin
// 根项目 build.gradle.kts
val springBootVersion by extra("3.2.0")
val junitVersion by extra("5.10.1")

subprojects {
    val springBootVersion: String by rootProject.extra
    
    dependencies {
        "testImplementation"("org.junit.jupiter:junit-jupiter:${rootProject.extra["junitVersion"]}")
    }
}

方式三:buildSrc 的版本常量

kotlin
// buildSrc/src/main/kotlin/Versions.kt
object Versions {
    const val SPRING_BOOT = "3.2.0"
    const val JUNIT = "5.10.1"
    const val GUAVA = "32.0.1-jre"
}

object Libs {
    const val SPRING_BOOT_WEB = "org.springframework.boot:spring-boot-starter-web:${Versions.SPRING_BOOT}"
    const val JUNIT_JUPITER = "org.junit.jupiter:junit-jupiter:${Versions.JUNIT}"
}
kotlin
// 子项目中使用
dependencies {
    implementation(Libs.SPRING_BOOT_WEB)
    testImplementation(Libs.JUNIT_JUPITER)
}

方式四:共享 BOM

kotlin
// 创建专用 BOM 子项目
// bom/build.gradle.kts
plugins {
    `java-platform`
}

dependencies {
    constraints {
        api("org.springframework.boot:spring-boot-starter-web:3.2.0")
        api("org.junit.jupiter:junit-jupiter:5.10.1")
    }
}
kotlin
// 其他子项目引入 BOM
dependencies {
    implementation(platform(project(":bom")))
    implementation("org.springframework.boot:spring-boot-starter-web")
}

推荐方案对比

方案优点缺点适用场景
版本目录官方推荐,TOML 简洁,IDE 支持好需要 Gradle 7.4+新项目首选
extra 属性简单,无需额外文件类型不安全小型项目
buildSrc 常量类型安全,可复用逻辑需要 buildSrc中大型项目
BOM 子项目可发布共享配置复杂需要发布 BOM 给外部使用

下一步