将平台约束应用于所有配置

Has*_*yed 5 gradle

如何以符合人体工程学的方式继承所有配置的 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'))
}
Run Code Online (Sandbox Code Playgroud)

Bjø*_*ter 6

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

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

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

// Groovy DSL
dependencies {
   implementation platform('x:y:z') // or api
   annotationProcessor platform('x:y:z')
}
Run Code Online (Sandbox Code Playgroud)

我认为这更具可读性和更精确。

一个常见的用例是 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'
}
Run Code Online (Sandbox Code Playgroud)

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