Skip to content

依赖锁定

依赖锁定(Dependency Locking)将解析后的依赖版本记录到锁文件中,确保每次构建使用完全相同的依赖版本,实现可重现构建

启用依赖锁定

kotlin
// build.gradle.kts
dependencyLocking {
    lockAllConfigurations()
}

生成锁文件

bash
# 首次生成锁文件(解析并记录所有版本)
./gradlew dependencies --write-locks

# 更新锁文件(依赖升级后)
./gradlew dependencies --update-locks com.google.guava:guava

# 更新所有锁
./gradlew dependencies --write-locks

生成的锁文件 gradle/dependency-locks/compileClasspath.lockfile

# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
com.fasterxml.jackson.core:jackson-annotations:2.15.3=compileClasspath,runtimeClasspath
com.fasterxml.jackson.core:jackson-core:2.15.3=compileClasspath,runtimeClasspath
com.fasterxml.jackson.core:jackson-databind:2.15.3=compileClasspath,runtimeClasspath
com.google.guava:guava:32.0.1-jre=compileClasspath,runtimeClasspath
...

将锁文件提交到 Git! 这样所有人和 CI 使用相同版本。

验证锁文件

bash
# 正常构建会验证锁文件(版本不一致则失败)
./gradlew build

# 检查是否有不在锁文件中的依赖
./gradlew dependencies --strict-lock

针对特定配置锁定

kotlin
dependencyLocking {
    // 只锁定运行时相关配置
    lockSpecificConfigurations("runtimeClasspath", "compileClasspath")
    
    // 锁文件位置(默认:gradle/dependency-locks/)
    lockFile.set(file("gradle.lockfile"))
}

忽略特定依赖

kotlin
dependencyLocking {
    lockAllConfigurations()
    ignoredDependencies.add("org.example:*")  // 不锁定这个组的依赖
}

与 SNAPSHOT 版本

SNAPSHOT 版本默认不被锁定。如需锁定:

kotlin
configurations.all {
    resolutionStrategy.cacheChangingModulesFor(0, TimeUnit.SECONDS)
}

下一步