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

如何在Gradle中配置Spotless以遵循Checkstyle自定义配置文件格式化代码

Gradle配置Spotless使用自定义Checkstyle规则

1. 引入Spotless插件

在项目根目录的build.gradle(Groovy DSL)或build.gradle.kts(Kotlin DSL)中添加Spotless插件依赖:

Groovy DSL

plugins {
    id 'com.diffplug.spotless' version '6.25.0' // 使用最新稳定版本
}

Kotlin DSL

plugins {
    id("com.diffplug.spotless") version "6.25.0"
}

2. 配置Spotless关联自定义Checkstyle规则

指定根目录下的config.xml作为Checkstyle规则文件,同时定义需要格式化的Java代码范围:

Groovy DSL

spotless {
    java {
        checkstyle {
            config file("config.xml") // 指向根目录的自定义Checkstyle配置
            // 可选:排除无需检查/格式化的文件
            // exclude '**/generated/**'
        }
    }
}

Kotlin DSL

spotless {
    java {
        checkstyle {
            config(file("config.xml"))
            // exclude("**/generated/**")
        }
    }
}

3. 可选:指定Checkstyle版本

如果你的自定义配置依赖特定版本的Checkstyle,可在checkstyle块中指定版本:

Groovy DSL

checkstyle {
    config file("config.xml")
    toolVersion '10.12.6' // 替换为你的目标Checkstyle版本
}

Kotlin DSL

checkstyle {
    config(file("config.xml"))
    toolVersion("10.12.6")
}

4. 常用命令

  • ./gradlew spotlessCheck:检查代码是否符合规则,仅输出问题不修改代码
  • ./gradlew spotlessApply:自动格式化代码,使其符合config.xml定义的规则

内容的提问来源于stack exchange,提问作者Aayush Bajaj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 10:42:14