Getting version of a dependency resolved with resolutionStrategy

To keep Spring dependencies in the same version I use:

resolutionStrategy.eachDependency { details ->
    if ( == 'org.springframework') { details.useVersion "4.1.3.RELEASE" }

and later just:

compile "org.springframework:spring-context"

without specified version.

It works fine, but maven-publish does not set a version tag in generated pom.xml. I could add missing tags with:

pom.withXml {
    asNode().dependencies[0]?.get('dependency')?.each() { dep -> ... }

but ‘project.configurations.compile.allDependencies’ does not have the version set as well (is null).

Question. How can I take a version resolved in the resolutionStrategy closure?

I have found Justin Ryan’s code example and the following hack seems to work.

def scopeToConfMapping = [compile: 'compile', runtime: 'runtime', testRuntime: 'test']
def scopeResolutionMap = scopeToConfMapping.collectEntries { confName, scope ->
    Configuration runtimeConfiguration = project.configurations.getByName(confName)
    ResolutionResult resolution = runtimeConfiguration.incoming.resolutionResult // Forces resolve of configuration
    Map<ModuleIdentifier, ResolvedComponentResult> resolutionMap = resolution.getAllComponents().collectEntries { ResolvedComponentResult versionResult ->
        [versionResult.moduleVersion.module, versionResult]
    [scope, resolutionMap]
asNode().dependencies[0]?.get('dependency')?.each() { dep ->
    String pomVer = dep.get("version").text();
    String name = dep.get("artifactId").text();
    String group = dep.get("groupId").text();
    String scope = dep.get("scope").text();
      def id = new org.gradle.api.internal.artifacts.DefaultModuleIdentifier(group, name)
    ResolvedComponentResult versionResult = scopeResolutionMap.get(scope).get(id)
    if(versionResult != null) {
        if (!dep.version) {
            dep.appendNode('version', versionResult.moduleVersion.version)
        } else {
            dep.version[0].value = versionResult.moduleVersion.version
    } else {
        if (pomVer.isEmpty()) {
            throw new StopExecutionException("Unable to find dependency version to put into pom.xml (dependency: $group:$name)")

Nevertheless I hope there is a better way. It should be a part of ‘maven-publish’ plugin - pom.xml generation is crucial to put the artifacts into an artifacts repository…

1 Like