平台用于确保项目中的所有依赖项都符合一致的版本集。
平台可帮助您管理和强制不同模块或库之间的版本一致性,尤其是在您使用一组需要保持同步的相关依赖项时。
使用平台
平台是一种专门的软件组件,用于控制传递依赖项版本。通常,它由推荐或强制特定版本的依赖项约束组成。当您需要在多个项目之间共享一致的依赖项版本时,平台特别有用。
在典型的设置中,您有
-
平台项目:它定义了跨不同子项目使用的依赖项的约束。
-
多个子项目:它们依赖于平台并声明依赖项,而不指定版本。
java-platform 插件
支持在 Java 生态系统中创建平台。平台也通常以 Maven BOM(物料清单)的形式发布,Gradle 原生支持此功能。
要使用平台,请使用 platform
关键字声明依赖项
dependencies {
// get recommended versions from the platform project
api(platform(project(":platform")))
// no version required
api("commons-httpclient:commons-httpclient")
}
dependencies {
// get recommended versions from the platform project
api platform(project(':platform'))
// no version required
api 'commons-httpclient:commons-httpclient'
}
此表示法会自动执行以下几项操作
-
将
org.gradle.category
属性设置为 platform,确保 Gradle 选择平台组件。 -
默认启用
endorseStrictVersions
行为,强制执行平台中定义的严格版本。
如果不需要严格版本强制执行,您可以使用 doNotEndorseStrictVersions
方法禁用它。
创建平台
在 Java 项目中,java-platform
插件与依赖项约束结合使用可以创建平台
plugins {
id("java-platform")
}
dependencies {
constraints {
api("com.google.guava:guava:30.1-jre")
api("org.apache.commons:commons-lang3:3.12.0")
}
}
这定义了一个自定义平台,其中包含 guava
和 commons-lang3
的特定版本,这些版本可以应用于其他项目。
导入平台
Gradle 支持导入 BOMs,它们是包含 <dependencyManagement>
部分的 POM 文件,用于管理依赖项版本。
要符合 BOM 的条件,.pom
文件需要设置 pom。这意味着 POM 文件应该在其元数据中明确指定 <packaging>pom</packaging>。
Gradle 将 BOM 块中的所有条目视为类似于添加依赖项约束。
常规平台
要导入 BOM,请使用 platform
依赖项修饰符方法声明对其的依赖项
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")
}
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 BOM 提供了 gson
和 dom4j
的版本,因此不需要显式版本。
强制平台
enforcedPlatform
关键字可用于覆盖依赖项图中找到的任何版本,但应谨慎使用,因为它实际上是传递的,并将强制版本导出到项目的所有消费者
dependencies {
// import a BOM. The versions used in this file will override any other version found in the graph
implementation(enforcedPlatform("org.springframework.boot:spring-boot-dependencies:1.5.8.RELEASE"))
// define dependencies without versions
implementation("com.google.code.gson:gson")
implementation("dom4j:dom4j")
// this version will be overridden by the one found in the BOM
implementation("org.codehaus.groovy:groovy:1.8.6")
}
dependencies {
// import a BOM. The versions used in this file will override any other version found in the graph
implementation enforcedPlatform('org.springframework.boot:spring-boot-dependencies:1.5.8.RELEASE')
// define dependencies without versions
implementation 'com.google.code.gson:gson'
implementation 'dom4j:dom4j'
// this version will be overridden by the one found in the BOM
implementation 'org.codehaus.groovy:groovy:1.8.6'
}
当使用 enforcedPlatform
时,如果您的软件组件旨在供他人使用,请谨慎行事。此声明是传递的,会影响您的消费者的依赖项图。如果他们不同意任何强制版本,他们将需要使用 exclude
。相反,如果您的可重用组件强烈倾向于特定的第三方依赖项版本,请考虑使用带有 strictly
的富版本声明。