Home > Back-end >  How to override a transative dependency in a gradle Java Platfrom Module?
How to override a transative dependency in a gradle Java Platfrom Module?

Time:12-31

I am using the Gradle Java Platfom Plugin Like so


plugins {
    `java-platform`
}


javaPlatform {
    allowDependencies()
}

dependencies {
    api(platform("org.springframework.boot:spring-boot-dependencies:2.7.7"))
}

I want to override the version of a dependency that the BOM will pull in. For example, change the version of spring security selected by the BOM from 5.7 to 5.8.

This seems to work


plugins {
   `java-platform`
}


javaPlatform {
   allowDependencies()
}

dependencies {
   api(platform("org.springframework.boot:spring-boot-dependencies:2.7.7"))
}
constraints {      
       api(group="org.springframework.security",name="spring-security-web") {
           version {
               require("5.8.1")
           }
       }

       api(group="org.springframework.security",name="spring-security-config") {
           version {
               require("5.8.1")
           }
       }
}

I have to put a constraints on every jar file in the spring security. I want to set the same version for all jars in the same group. My questions:

  • what is the correct way to override a dependency form a BOM?
  • Is there a way to override a depedency version for a group rather than a specific jar? if yes how?

CodePudding user response:

In the instance of Spring Security, it has a BOM that you can define in your Java Platform.

plugins {
  `java-platform`
}

javaPlatform {
  allowDependencies()
}

dependencies {
  api(platform("org.springframework.boot:spring-boot-dependencies:2.7.7"))

  // import the Spring Security BOM
  api(platform("org.springframework.security:spring-security-bom:5.8.1"))
}

If there were no published BOM, then in Gradle it's possible to define your own using a dependency version alignment rule.

// build.gradle.kts

// Create a rule that defines a 'virtual platform'
abstract class SpringSecurityAlignmentRule: ComponentMetadataRule {
  override fun execute(ctx: ComponentMetadataContext) {
    ctx.details.run {
      if (id.group.startsWith("org.springframework.security")) {
        // declare that Spring Security modules all belong to the Spring Security virtual platform
        belongsTo("org.springframework.security:spring-security-virtual-platform:${id.version}")
      }
    }
  }
}

dependencies {
  // apply the rule
  components.all<SpringSecurityAlignmentRule>()    
  // set the virtual Spring Security platform to 5.8.1
  implementation(platform("org.springframework.security:spring-security-virtual-platform:5.8.1"))
}
  • Related