Gradle - 排除配置的依赖关系,但不排除继承配置的依赖关系

2024-02-28

使用 Gradle 1.0 里程碑 8。

我的项目使用 slf4j+Logback 进行日志记录,因此我想防止 log4j 上的任何传递依赖项污染我的类路径。因此,我添加了全局排除,如下所示:

configurations {
    all*.exclude group: "log4j", module: "log4j"
}

但是,我正在使用测试库(hadoop-minicluster)它对 log4j 有运行时依赖性,所以我现在需要允许我的测试运行时有 log4j 依赖性。我尝试添加对 log4j 的直接依赖:

testRuntime group: "log4j", name: "log4j", version: "1.2.15"

并编辑我的排除代码(有点黑客):

configurations.findAll {!it.name.endsWith('testRuntime')}.each { conf ->
    conf.exclude group: "log4j", module: "log4j"
}

但这是行不通的。将排除添加到 testCompile conf 会自动将其添加到所有继承配置中,包括 testRuntime。似乎这种排除甚至覆盖了我添加的显式依赖项。

这似乎是 Gradle 的预期行为。从the docs http://gradle.org/docs/current/userguide/dependency_management.html:

如果您为特定配置定义排除,则在解析此配置时,将为所有依赖项过滤排除的传递依赖项或任何继承配置.

那么还有其他方法可以实现我想要实现的目标吗?

Ideas:

  • Create a new conf myTestRuntime that does not extend from testCompile, and use that for my test classpath.
    • 但随后我必须复制 testCompile 和 myTestRuntime 的所有依赖项。
  • Remove config-level exclusions. For all confs apart from testRuntime, loop through dependencies and manually remove log4j (or add a dep-level exclusion on log4j).
    • 这可能吗? Configuration.allDependency 是只读的。

目前我已经设法解决了这个问题,但我仍然欢迎任何更好的解决方案。

这是我最终所做的:

  • 仅为 log4j 添加新配置:

    log4j(group: 'log4j', name: 'log4j', version: '1.2.15') {
        transitive = false
    }
    
  • 保留除该配置之外的所有配置的配置级排除:

    configurations.findAll {!it.name.endsWith('log4j')}.each { conf ->
        conf.exclude group: "log4j", module: "log4j"
    }
    
  • 将 log4j 配置添加到我的测试的类路径中:

    test {
        classpath += configurations.log4j
    }
    

这样我们就可以将 log4j.jar 放到类路径中,即使它被排除在 testRuntime 配置之外。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Gradle - 排除配置的依赖关系,但不排除继承配置的依赖关系 的相关文章

随机推荐