在 Gradle 中,可以使用平台和版本目录等多种技术来集中管理依赖项。每种方法都有其优点,并有助于高效地集中和管理依赖项。

使用平台

平台是一组依赖约束,旨在管理库或应用程序的传递依赖项。

当您在 Gradle 中定义平台时,您本质上是在指定一组旨在一起使用的依赖项,从而确保兼容性并简化依赖管理。

platform/build.gradle.kts
plugins {
    id("java-platform")
}

dependencies {
    constraints {
        api("org.apache.commons:commons-lang3:3.12.0")
        api("com.google.guava:guava:30.1.1-jre")
        api("org.slf4j:slf4j-api:1.7.30")
    }
}
platform/build.gradle
plugins {
    id("java-platform")
}

dependencies {
    constraints {
        api("org.apache.commons:commons-lang3:3.12.0")
        api("com.google.guava:guava:30.1.1-jre")
        api("org.slf4j:slf4j-api:1.7.30")
    }
}

然后,您可以在项目中使用该平台

app/build.gradle.kts
plugins {
    id("java-library")
}

dependencies {
    implementation(platform(project(":platform")))
}
app/build.gradle
plugins {
    id("java-library")
}

dependencies {
    implementation(platform(":platform"))
}

在这里,platform 定义了 commons-lang3guavaslf4j-api 的版本,确保它们兼容。

Maven 的 BOM(物料清单)是 Gradle 支持的一种流行的平台类型。BOM 文件列出了具有特定版本的依赖项,允许您以集中方式管理这些版本。

一个流行的平台是 Spring Boot 物料清单。要使用 BOM,请将其添加到项目的依赖项中

build.gradle.kts
dependencies {
    // import a BOM
    implementation(platform("org.springframework.boot:spring-boot-dependencies:1.5.8.RELEASE"))
    // define dependencies without versions
    implementation("com.google.code.gson:gson")
    implementation("dom4j:dom4j")
}
build.gradle
dependencies {
    // import a BOM
    implementation platform('org.springframework.boot:spring-boot-dependencies:1.5.8.RELEASE')
    // define dependencies without versions
    implementation 'com.google.code.gson:gson'
    implementation 'dom4j:dom4j'
}

通过包含 spring-boot-dependencies 平台依赖项,您可以确保所有 Spring 组件都使用 BOM 文件中定义的版本。

使用版本目录

版本目录是依赖坐标的集中列表,可以在多个项目中引用。您可以在构建脚本中引用此目录,以确保每个项目都依赖于一组通用的已知依赖项。

首先,在项目的 gradle 目录中创建 libs.versions.toml 文件。此文件将定义您的依赖项和插件的版本

gradle/libs.versions.toml
[versions]
groovy = "3.0.5"
checkstyle = "8.37"

[libraries]
groovy-core = { module = "org.codehaus.groovy:groovy", version.ref = "groovy" }
groovy-json = { module = "org.codehaus.groovy:groovy-json", version.ref = "groovy" }
groovy-nio = { module = "org.codehaus.groovy:groovy-nio", version.ref = "groovy" }
commons-lang3 = { group = "org.apache.commons", name = "commons-lang3", version = { strictly = "[3.8, 4.0[", prefer="3.9" } }

[bundles]
groovy = ["groovy-core", "groovy-json", "groovy-nio"]

[plugins]
versions = { id = "com.github.ben-manes.versions", version = "0.45.0" }

然后,您可以在构建文件使用版本目录

build.gradle.kts
plugins {
    `java-library`
    alias(libs.plugins.versions)
}

dependencies {
    api(libs.bundles.groovy)
}
build.gradle
plugins {
    id 'java-library'
    alias(libs.plugins.versions)
}

dependencies {
    api libs.bundles.groovy
}