DEBUG.WIKI
ZgoCloud:多地区部署,按需选节点;日本、美国、香港、德国
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS
晚安云;香港 CN2 ¥15/月

解决 Gradle 报错 Configuration cache problems found 序列化失效修复

排查 Gradle 开启 --configuration-cache 后编译报 Configuration cache state could not be cached,分析 任务输入包含不可序列化对象与直接访问 Project 实例。

问题现象

开启 Gradle 新特性配置缓存(--configuration-cache)时,构建报错退出:

FAILURE: Build failed with an exception.
* What went wrong:
Configuration cache problems found in this build.
- Task `:app:customTask` of type `com.example.CustomTask`: cannot serialize field `project` of type `org.gradle.api.internal.project.DefaultProject`

触发根因

  1. Gradle 配置缓存要求任务的配置状态必须能够在两次构建之间完整持久化到磁盘;
  2. 自定义插件或任务中直接持有了 Project、Gradle 或 Settings 等动态巨型非瞬态对象;
  3. 未遵循现代 Gradle 官方推行的 Lazy Provider API(Property<T>)规范。

解决步骤

打开 Gradle 生成的 HTML 配置缓存分析报告

在终端点击或浏览器打开:

file:///path/to/project/build/reports/configuration-cache/.../configuration-cache-report.html

查看具体导致无法序列化的字段和调用行号。

重构自定义任务使用 Provider API 替换直接持有 project 实例

消除直接引用:

abstract class CustomTask : DefaultTask() {
    @get:Input
    abstract val appVersion: Property<String>

    @get:OutputFile
    abstract val outputFile: RegularFileProperty

    @TaskAction
    fun execute() {
        outputFile.get().asFile.writeText("Version: ${appVersion.get()}")
    }
}

验证确认

重新执行构建:

./gradlew build --configuration-cache

首次运行成功固化配置状态,二次构建彻底跳过整个 Configuration 阶段,提速数十秒。