Skip to content

SpotBugs 静态分析

SpotBugs 是 FindBugs 的继任者,通过静态分析字节码检测潜在的 Bug。

基本配置

kotlin
plugins {
    java
    id("com.github.spotbugs") version "6.0.6"
}

spotbugs {
    toolVersion.set("4.8.3")
    excludeFilter.set(file("config/spotbugs/exclude.xml"))
    effort.set(com.github.spotbugs.snom.Effort.MAX)    // 分析力度
    reportLevel.set(com.github.spotbugs.snom.Confidence.MEDIUM)  // 报告级别
    ignoreFailures.set(false)
}

// 生成 HTML 报告(默认 XML)
tasks.withType<com.github.spotbugs.snom.SpotBugsTask> {
    reports.create("html") {
        required.set(true)
        outputLocation.set(layout.buildDirectory.file("reports/spotbugs/${name}.html"))
        setStylesheet("fancy-hist.xsl")
    }
    reports.create("xml") {
        required.set(false)
    }
}

排除规则

xml
<!-- config/spotbugs/exclude.xml -->
<FindBugsFilter>
    <!-- 排除 Lombok 生成的代码 -->
    <Match>
        <Class name="~.*\$Builder" />
    </Match>
    
    <!-- 排除特定 Bug 类型 -->
    <Match>
        <Bug pattern="EI_EXPOSE_REP2"/>
    </Match>
    
    <!-- 排除特定包 -->
    <Match>
        <Package name="com.example.generated"/>
    </Match>
</FindBugsFilter>

常用 Bug 模式

Bug 模式说明
NP_NULL_ON_SOME_PATH空指针解引用
EQ_COMPARETO_USE_OBJECT_EQUALScompareTo 与 equals 不一致
SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTESQL 注入风险
DM_DEFAULT_ENCODING使用平台默认编码
STYLE代码风格问题

运行检查

bash
# 检查主代码
./gradlew spotbugsMain

# 检查测试代码
./gradlew spotbugsTest

# 查看报告
# build/reports/spotbugs/main.html

下一步