本指南解释了如何使用依赖约束来管理和升级 Gradle 中传递性依赖的版本。

为什么要升级传递性依赖?

升级依赖版本的原因有很多

  • 错误修复解决旧版本中存在的问题。

  • 安全补丁解决漏洞以确保项目安全。

  • 性能改进使构建更快、更高效。

  • 新功能提供额外功能和更好的兼容性。

第 1 步:设置传递性依赖的依赖约束

依赖约束允许您定义直接依赖和传递性依赖的版本版本范围

依赖约束还可以覆盖传递性依赖并强制执行严格版本,甚至在必要时进行降级

要强制执行传递性依赖的特定版本,请在dependencies {}内部使用constraints

build.gradle.kts
dependencies {
    implementation("org.apache.httpcomponents:httpclient") // No version specified
    constraints {
        implementation("org.apache.httpcomponents:httpclient:4.5.3") {
            because("previous versions have a bug impacting this application")
        }
        implementation("commons-codec:commons-codec:1.11") {
            because("version 1.9 pulled from httpclient has bugs affecting this application")
        }
    }
}
build.gradle
dependencies {
    implementation("org.apache.httpcomponents:httpclient") // No version specified
    constraints {
        implementation("org.apache.httpcomponents:httpclient:4.5.3") {
            because("previous versions have a bug impacting this application")
        }
        implementation("commons-codec:commons-codec:1.11") {
            because("version 1.9 pulled from httpclient has bugs affecting this application")
        }
    }
}
  • implementation依赖省略了版本

  • constraints强制执行httpclientcommons-codec特定版本

  • commons-codec的约束仅在其被传递性拉取时才适用

运行./gradlew dependencies --configuration runtimeClasspath显示结果

dependencies.out
> Task :dependencies

------------------------------------------------------------
Root project 'how_to_upgrade_transitive_dependencies'
------------------------------------------------------------

compileClasspath - Compile classpath for source set 'main'.
+--- org.apache.httpcomponents:httpclient -> 4.5.3
|    +--- org.apache.httpcomponents:httpcore:4.4.6
|    +--- commons-logging:commons-logging:1.2
|    \--- commons-codec:commons-codec:1.9 -> 1.11
+--- org.apache.httpcomponents:httpclient:4.5.3 (c)
\--- commons-codec:commons-codec:1.11 (c)

总结

在以下情况下使用依赖约束:

  • 您想要使用特定版本覆盖传递性依赖

  • 您需要跨多个依赖项强制执行严格的版本或范围

  • 您想要防止依赖冲突,而无需手动添加传递性依赖。