首页 > 解决方案 > 将平台约束应用于所有配置

问题描述

如何以符合人体工程学的方式从 BOM 继承所有配置的约束?以下是我目前的做法。我在 Gradle 6.6.1 上。

dependencies {
    compileOnly(platform('x:y:z'))
    implementation(platform('x:y:z'))
    annotationProcessor(platform('x:y:z'))
    testAnnotationProcessor(platform('x:y:z'))
    testImplementation(platform('x:y:z'))
    testCompileOnly(platform('x:y:z'))
}

标签: gradle

解决方案


好吧,你可以通过滥用这样的configurations.all方法来做到这一点:

// Groovy DSL
configurations.all { config ->
    project.dependencies.add(config.name, project.dependencies.platform('x:y:z'))
}

但是您不需要首先将平台添加到所有这些配置中。因为它们中的大多数都是可解析的并且扩展了apiand implementation,所以您通常只需将其添加到其中之一。唯一的例外是annotationProcessor,它是孤立的(但由 扩展testAnnotationProcessor)。因此,您仍然可以将其减少为:

// Groovy DSL
dependencies {
   implementation platform('x:y:z') // or api
   annotationProcessor platform('x:y:z')
}

在我看来,这更具可读性和更精确。

一个常见的用例是 Spring Boot。它可能看起来像这样:

// Groovy DSL
import org.springframework.boot.gradle.plugin.SpringBootPlugin

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.4.2'
}

dependencies {
    // BOMS (Note that using the "BOM_COORDINATES" variable makes it match the version of the plugin)
    implementation platform(SpringBootPlugin.BOM_COORDINATES)
    annotationProcessor platform(SpringBootPlugin.BOM_COORDINATES)

    // Actual dependencies
    implementation 'org.springframework.boot:spring-boot-starter'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
}

有趣的是,在这个确切的用例上有一个Gradle 问题。在这里,他们解释说通常您不需要此功能,并且在您做的地方最好明确说明它,而不是仅仅将一组依赖版本“锤击”到所有东西上。


推荐阅读