You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gradle 6.5.1自定义resolutionStrategy后依赖exclude规则不生效如何解决

问题原因

Gradle 6.5.1 版本的依赖解析优先级设计中,自定义 resolutionStrategy 的优先级天然高于单依赖声明中配置的 exclude 规则,只要你在全局/配置级的 resolutionStrategy 中修改了组件的解析逻辑,对应的单依赖排除规则就会被覆盖,该版本没有内置开关可以实现“自定义策略不适用时自动回退默认策略”的效果。

可行解决方案
  • 方案1:将排除规则迁移到 resolutionStrategy 内配置,保证优先级一致
    如果需要全局生效对应的排除规则,直接在对应配置的 resolutionStrategy 中添加排除逻辑即可,示例如下:
configurations.testImplementation {
    resolutionStrategy {
        // 保留你原有的自定义解析逻辑
        // 新增排除规则
        exclude group: 'org.typelevel', module: 'cats-core_2.12'
        exclude group: 'org.scala-lang', module: 'scala-library'
    }
}

如果只需要排除 com.example:foo-bar_2.12 传递的对应依赖,不想影响其他依赖的引入,可以结合 componentSelection 做条件判断:

configurations.testImplementation {
    resolutionStrategy {
        componentSelection {
            all { ComponentSelection selection ->
                // 仅对foo-bar传递的依赖做排除
                def isFromFooBar = selection.requested.selectors.any { 
                    it instanceof ModuleComponentSelector && 
                    it.group == 'com.example' && 
                    it.name == 'foo-bar_2.12' 
                }
                if (isFromFooBar) {
                    if (selection.candidate.group == 'org.typelevel' && selection.candidate.name == 'cats-core_2.12') {
                        selection.reject("排除foo-bar传递的cats-core依赖")
                    }
                    if (selection.candidate.group == 'org.scala-lang' && selection.candidate.name == 'scala-library') {
                        selection.reject("排除foo-bar传递的scala-library依赖")
                    }
                }
            }
        }
        // 保留你原有的自定义解析逻辑
    }
}
  • 方案2:收窄自定义 resolutionStrategy 的生效范围
    修改你现有自定义解析策略的逻辑,不要全局干预所有依赖的解析规则,仅针对你需要自定义处理的特定组件做配置,其余组件保持默认解析逻辑,单依赖声明的 exclude 规则即可正常生效。

  • 方案3:升级Gradle版本到7.0及以上
    Gradle 7.0 版本官方修复了该优先级冲突问题,优化后单依赖声明的 exclude 规则优先级会高于全局解析策略的通用配置,无需额外修改即可让你原有配置生效,是长期来看最省心的解决方案。


内容的提问来源于stack exchange,提问作者Robin Green

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 00:36:03