如何在Gradle生成的POM文件中排除依赖项

9

我正在使用“maven”插件将由Gradle构建创建的工件上传到Maven中央仓库。 我正在使用类似以下任务的任务:

uploadArchives {
  repositories {
    mavenDeployer {
      beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }

      pom.project {
        name 'Example Application'
        packaging 'jar'
        url 'http://www.example.com/example-application'

        scm {
          connection 'scm:svn:http://foo.googlecode.com/svn/trunk/'

          url 'http://foo.googlecode.com/svn/trunk/'
        }

        licenses {
          license {
            name 'The Apache License, Version 2.0'
            url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
          }
        }

      }
    }
  }
}

然而,该任务创建的POM文件并未正确报告已在我的Gradle构建文件中排除的依赖项。例如:

dependencies {
    compile('org.eclipse.jgit:org.eclipse.jgit.java7:3.5.2.201411120430-r') { exclude module: 'commons-logging' }
    compile('com.upplication:s3fs:0.2.8') { exclude module: 'commons-logging' }
}

如何在生成的POM文件中正确管理排除的依赖项?
3个回答

11

您可以通过过滤掉不需要的依赖项来简单地覆盖pom的依赖关系,例如,要排除junit,您可以将以下行添加到mavenDeployer配置中:

pom.whenConfigured {
    p -> p.dependencies = p.dependencies.findAll { 
        dep -> dep.artifactId != "junit" 
    }
}

5
在Gradle依赖中使用“exclude”通常是正确的答案,但我仍然需要从POM中删除一些我的“runtimeOnly”依赖项,这导致我查看了此StackOverflow页面。使用Gradle 4.7进行测试似乎表明,使用“compileOnly”会完全从pom中排除该依赖项,但“runtimeOnly”会在pom中添加一个“runtime”依赖项,在我的情况下不是我想要的。我无法找到一种标准的Gradle方法来从POM中排除运行时依赖项。
另一个答案中显示的pom.whenConfigured方法适用于旧版“maven”插件发布,但对于更新的“maven-publish”插件无效。我的实验结果为“maven-publish”:
publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
            pom.withXml {
                asNode().dependencies.dependency.each { dep ->
                  if(dep.artifactId.last().value().last() in ["log4j", "slf4j-log4j12"]) {
                      assert dep.parent().remove(dep)
                  }
                }
            }
        }
    }
}

3
问题是在exclude定义中只指定了模块,而没有指定组。
将它们两个都添加进去,排除项就会正确地添加到POM文件中。例如:
compile('org.eclipse.jgit:org.eclipse.jgit.java7:3.5.2.201411120430-r') { 
    exclude group: 'commons-logging', module: 'commons-logging' 
}
compile('com.upplication:s3fs:0.2.8') { 
    exclude group: 'commons-logging', module: 'commons-logging' 
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接