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

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

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

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

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

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

  • 新特性 提供附加功能和更好的兼容性。

步骤 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)

总结

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

  • 你想用特定版本 覆盖传递性依赖 时。

  • 你需要跨多个依赖项强制使用 严格版本或范围 时。

  • 你想 防止依赖冲突 而无需手动添加传递性依赖项时。