Dependency constraints exclude

I’m trying to figure out what would be the correct way to exclude transitive dependency from a specific dependency for all projects. Basically I’m trying to achieve what Spring dependency management plugin does but with Gradle’s dependency constraints: https://docs.spring.io/dependency-management-plugin/docs/current-SNAPSHOT/reference/html/#dependency-management-configuration-dsl-exclusions

So far I figured I can do the following in the root build.gradle.kts to control the dependency versions:

plugins {
    java
}

subprojects {
    apply {
        plugin("java")
    }

    repositories {
        mavenCentral()
    }

    dependencies {
        constraints {
            dependency("some:dependency")
        }
    }
}

fun DependencyConstraintHandler.dependency(constraintNotation: Any) {
    configurations.all {
        add(name, constraintNotation)
    }
}

I though struggle to find the way to exclude transitive dependency of a specific dependency in a centralized way. I know I can exclude the dependency completely from the configuration, but that’s too much as sometimes I still need to keep a transitive dependency for one of the dependencies.

Is there a way of doing it without defining the exclude in every module where the dependency is imported?

It’s not kotlin, but i managed to do it this way :

subprojects {
    afterEvaluate {
        configurations.each { Configuration conf ->
            conf.dependencies.each { Dependency dep ->
                if (dep.name == 'xxxx') {
                    // I know this is a ModuleDependency type, exclude() is availabe
                    dep.exclude group: 'org.codehaus.castor', module: 'castor-xml'
                }
            }
        }
    }
}

Hey @ulk200 :slight_smile:
Thanks for your snippet. Indeed it worked this way. Though I’m not entirely happy with the my solution as I parse the dependency notation from string and have to pass the subproject to the method, but seems to work. Maybe it will be useful for someone :slight_smile:

subprojects {
    apply {
        plugin("java")
    }

    repositories {
        mavenCentral()
    }

    dependencies {
        constraints {
            dependency(this@subprojects, "group:name:version") {
                exclude(group = "group")
            }
        }
    }

}

fun DependencyConstraintHandler.dependency(project: Project, constraintNotation: String, action: Action<ModuleDependency>) {
    val parts = constraintNotation.split(":")
    val group = parts[0]
    val name = parts[1]
    project.configurations.all {
        add(this.name, constraintNotation)

        dependencies.whenObjectAdded {
            if (this is ModuleDependency && this.group == group && this.name == name) {
                action.execute(this)
            }
        }
    }
}