Appearance
统一版本管理
在多项目构建中,统一管理依赖版本避免各子项目使用不同版本带来的问题。
方式一:版本目录(推荐)
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 给外部使用 |
下一步
- buildSrc - 深入了解 buildSrc 模块
- 版本目录(Catalog) - 版本目录详细说明