记录Gradle中Checkstyle和Spotbugs的使用

Checkstyle 是一个开发工具,用于帮助程序员编写符合编码标准的 Java 代码。它自动化了检查 Java 代码的过程,使人们免于承担这项枯燥(但重要)的任务。这使得它成为希望实施编码标准的项目的理想选择。

SpotBugs 是一个在 Java 程序中发现 bug 的程序。它寻找“ bug 模式”的实例ーー可能是错误的代码实例。

  1. 项目目录结构:
projectRoot
| gradle
|    | libs.versions.toml
| buildSrc
|    | build.gradle
|    | settings.gradle
|    | src
|        | main
|            | groovy
|                | check.gradle
| config
|    | checkstyle
|    |   | checkstyle.xml
|    | findbugs
|    | exclude.xml
  1. Gradle版本管理

projectRoot/gradle/libs.versions.toml

[versions]
spotbugs-gradle-plugin= "5.0.13"
[libraries]
spotbugs-gradle-plugin = { module = "com.github.spotbugs.snom:spotbugs-gradle-plugin", version.ref = "spotbugs-gradle-plugin" }
 

projectRoot/buildSrc/setting.gradle

dependencyResolutionManagement {
    versionCatalogs {
        libs {
            from(files("../gradle/libs.versions.toml"))
 

projectRoot/buildSrc/build.gradle

plugins {
    id 'groovy-gradle-plugin'
repositories {
    gradlePluginPortal()
dependencies {
    implementation libs.spotbugs.gradle.plugin
  1. CheckStyle和Spotbugs约束

projectSrc/buildSrc/src/main/groovy/check.gradle

plugins {
    // checkstyle插件
    id 'checkstyle'
    // spotbugs 插件
    id 'com.github.spotbugs'
dependencies {
    spotbugsSlf4j group: 'org.slf4j', name: 'slf4j-api', version: '1.8.0-beta4'
    spotbugsSlf4j group: 'org.slf4j', name: 'slf4j-simple', version: '1.8.0-beta4'
spotbugs {
    // 是否显示堆栈
    showStackTraces = true
    // 查找器
    omitVisitors = [ 'FindNonShortCircuit' ]
    // 生产报告的目录
    reportsDir = file("$buildDir/spotbugs")
    // 包含匹配的文件
    File includeFile = new File("$rootDir/config/findbugs/include.xml")
    if (includeFile.exists()) {
        includeFilter = file("$rootDir/config/findbugs/include.xml")
    // 排除匹配的文件
    File excludeFile = new File("$rootDir/config/findbugs/exclude.xml")
    if (excludeFile.exists()) {
        excludeFilter = file("$rootDir/config/findbugs/exclude.xml")
    // 使用最大堆
    maxHeapSize = '1g'
// spotbugsMain 任务配置
spotbugsMain {
    reports {
        // 报告形式使用html形式
        html {
            required = true
            // 文件输出位置
            outputLocation = file("$buildDir/reports/spotbugs/main/spotbugs.html")
            // 样式形式
            stylesheet = 'fancy-hist.xsl'
// spotbugsTest 任务配置, 如上
spotbugsTest {
    reports {
        html {
            required = true
            outputLocation = file("$buildDir/reports/spotbugs/main/spotbugs.html")
            stylesheet = 'fancy-hist.xsl'
  1. CheckStyle和SpotBugs配置