Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

gradle - Applying platform constraints to all configurations

How do I inherit constraints from BOMs for all configurations in an ergonomic way ? The following is how I am currently doing it. I am on 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'))
}
question from:https://stackoverflow.com/questions/65842725/applying-platform-constraints-to-all-configurations

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, you could do it by abusing the configurations.all method like this:

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

But you don't need to add the platform to all those configurations in the first place. Because most of them are resolvable and extend both api and implementation, you typically only need to add it to one of those. The only exception is annotationProcessor, which is isolated (but is extended by testAnnotationProcessor). So you can still reduce it to:

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

This is in my opinion more readable and more precise.

A common use case is for Spring Boot. It could look like this:

// 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'
}

Interestingly, there is a Gradle issue on this exact use case. Here they explained that typically you don't need this functionality, and where you do it is better to be explicit about it rather than just "hammer" a set of dependency versions onto everything.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...