如果你需要一個自動化的工具幫助你或者你的團隊發現代碼中的缺陷,在提升代碼質量同時減少人工Code Review的成本,那這篇文章非常的適合你,本文圍繞SpotBugs與Gradle集成,將相關配置和使用進行了詳細介紹,并提供了各種能夠為你的專案定制化配置的手段,來源和出處都已在文中關鍵處以超鏈接給出,盡情享受吧,
SpotBugs是什么?
SpotBugs是一個開源的Java靜態分析工具,旨在幫助開發人員檢測代碼中的潛在缺陷和漏洞,SpotBugs可以通過掃描Java位元組碼來發現潛在的問題,例如空指標參考、型別轉換錯誤、未使用的變數等等,它還可以檢測代碼中的潛在安全漏洞,例如SQL注入、XSS攻擊等,SpotBugs提供了一個用戶友好的GUI和命令列介面,可以輕松地與各種構建工具和IDE集成,例如Ant、Maven、Gradle、Eclipse和IntelliJ IDEA,SpotBugs還支持插件和自定義規則,使得開發人員可以根據專案的特定需求和標準對其進行定制化配置,更多詳細資訊可以查看SpotBugs官方檔案,
SpotBugs是FindBugs的一個分支,它在FindBugs的基礎上進行了改進和升級,它使用了更先進的演算法和技術來提高分析的準確性和效率,SpotBugs還添加了對新的Java版本的支持,例如Java 8和Java 11,SpotBugs還提供了更好的用戶界面和命令列界面,并支持更多的構建工具和IDE集成,
FindBugs也是一款非常流行的Java靜態分析工具,但是已經停止更新,停更的原因似乎是專案擁有者不愿繼續在這個專案上花時間,代碼貢獻者因為沒有權限也無法繼續迭代和發布新的版本,在FindBugs GitHub首頁的README檔案中提供了兩個檔案專案狀態 2016-November和專案狀態 2017-September,里面講述了代碼貢獻者當時的一些擔憂和無奈,
SpotBugs與Gradle集成
開始之前先簡單介紹下本文中將會提到的幾個依賴以及它們之間的關系,以便于理解后續內容:
com.github.spotbugs.snom:spotbugs-gradle-plugin是一個Gradle插件,它將SpotBugs集成到 Gradle構建中,生成SpotBugsTask并可以通過配置屬性來擴展,com.github.spotbugs:spotbugs這個依賴基本包含了所有SpotBugs檢測器,這些檢測器實作了Bug descriptions中提到的相關Bug檢測項的邏輯,com.h3xstream.findsecbugs:findsecbugs-plugin在com.github.spotbugs:spotbugs的基礎上增加了安全相關的檢查器也就是Bug descriptions#Security中描述的相關檢查項,com.github.spotbugs:spotbugs-annotations是Spotbugs的一個擴展/輔助工具,開發者使用這里面注解可以讓Spotbugs按照我們的意圖來檢查代碼,
spotbugs-gradle-plugin
spotbugs-gradle-plugin是一個Gradle插件,它將SpotBugs集成到Gradle構建中,生成SpotBugsTask并提供相關配置來擴展,運行SpotBugsTask就可以執行檢查,生成報告等,
默認情況下,這個插件里面已經包含了一個spotbugs,所以應用了這個插件后一般無需在另外添加com.github.spotbugs:spotbugs,從SpotBugs version mapping中可以知道spotbugs-gradle-plugin不同版本中默認包含的spotbugs版本之間的關系,比如:com.github.spotbugs.snom:spotbugs-gradle-plugin:5.0.13包含了com.github.spotbugs:spotbugs:4.7.3,
SpotBugs Gradle插件要求Gradle版本為7.0或者更高,JDK版本為1.8或者更高,
這個插件會為每個sourceSets生成SpotBugsTask,例如專案中有兩個sourceSets main和test,插件將生成兩個SpotBugsTask(spotbugsMain和spotbugsTest),
如果不想自動生成SpotBugsTask,可以使用SpotBugs Base插件從頭開始配置,參考com.github.spotbugs-base,
生成的SpotBugsTask執行時需要編譯后的.class檔案作為輸入,因此它們將在Java編譯后運行,SpotBugs Gradle增加了check相關的任務依賴,所以簡單的運行./gradlew check也會執行生成的SpotBugsTask,
參考com.github.spotbugs在build.gradle檔案中增加以下內容來引入SpotBugs Gradle插件:
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "com.github.spotbugs.snom:spotbugs-gradle-plugin:5.0.13"
}
}
apply plugin: "com.github.spotbugs"
插件里面提供了很多可選的屬性來配置或者擴展插件的行為,
下面展示了在build.gradle檔案增加spotbugs{}相關屬性的例子,詳細資訊可以參考SpotBugsExtension,這里面有每個屬性作用、可指定的值和其他相關資訊,spotbugs{}中指定的大部分屬性將作為生成的SpotBugsTask配置的默認值,意味著可以通過spotbugs{}給所有SpotBugsTask配置屬性,
spotbugs {
ignoreFailures = false
showStackTraces = true
showProgress = false
reportLevel = 'default'
effort = 'default'
visitors = [ 'FindSqlInjection', 'SwitchFallthrough' ]
omitVisitors = [ 'FindNonShortCircuit' ]
reportsDir = file("$buildDir/reports/spotbugs")
includeFilter = file('spotbugs-include.xml')
excludeFilter = file('spotbugs-exclude.xml')
onlyAnalyze = ['com.foobar.MyClass', 'com.foobar.mypkg.*']
projectName = name
release = version
extraArgs = [ '-nested:false' ]
jvmArgs = [ '-Duser.language=ja' ]
maxHeapSize = '512m'
}
除了上述方式外,還可直接配置SpotBugsTask,以設定某個任務特定的屬性,比如下面為名為spotbugsMain的任務單獨進行了設定,跟spotbugs{}同名的屬性將被覆寫,詳細資訊參考SpotBugsTask,
spotbugsMain {
sourceDirs = sourceSets.main.allSource.srcDirs
classDirs = sourceSets.main.output
auxClassPaths = sourceSets.main.compileClasspath
reports {
html {
required = true
outputLocation = file("$buildDir/reports/spotbugs/main/spotbugs.html")
stylesheet = 'fancy-hist.xsl'
}
}
ignoreFailures = false
showStackTraces = true
showProgress = false
reportLevel = 'default'
effort = 'default'
visitors = [ 'FindSqlInjection', 'SwitchFallthrough' ]
omitVisitors = [ 'FindNonShortCircuit' ]
reportsDir = file("$buildDir/reports/spotbugs")
includeFilter = file('spotbugs-include.xml')
excludeFilter = file('spotbugs-exclude.xml')
baselineFile = file('spotbugs-baseline.xml')
onlyAnalyze = ['com.foobar.MyClass', 'com.foobar.mypkg.*']
projectName = name
release = version
extraArgs = [ '-nested:false' ]
jvmArgs = [ '-Duser.language=ja' ]
maxHeapSize = '512m'
}
后面將會有一段描述比較常用或者重要的屬性,
com.github.spotbugs:spotbugs
因為spotbugs-gradle-plugin中已經包含了spotbugs,所以一般情況下不需要再單獨引入這個依賴,不過可能因為默認帶的版本有Bug、需要跟IDEA的SpotBugs插件使用相同的版本,又或者新版本的檢測器新加了實用的檢測項等原因我們會需要單獨指定版本,下面提供了兩種方式實作,
在配置spotbugs-gradle-plugin的時候通過toolVersion指定spotbugs版本,
spotbugs {
toolVersion = '4.7.3'
}
在dependencies添加依賴并指定依賴版本,
dependencies {
spotbugs 'com.github.spotbugs:spotbugs:4.7.3'
}
findsecbugs-plugin
findsecbugs-plugin是Spotbugs的安全漏洞檢測插件,它在spotbugs的基礎上增加了自己的規則集,專注于檢測安全相關的問題,例如密碼泄漏、SQL 注入、XSS 等,也就是Bug descriptions#Security中描述的相關檢查項,
dependencies {
spotbugsPlugins 'com.h3xstream.findsecbugs:findsecbugs-plugin:1.12.0'
}
spotbugs-annotations
spotbugs-annotations是Spotbugs的一個擴展/輔助工具,里面提供了很多注解,我們可以在編碼時將它們加在被檢測代碼的相應位置(如屬性、方法、形參、本地變數),讓Spotbugs按照我們的意圖來檢查代碼,以便SpotBugs可以更恰當地發出警告,在Annotations中列舉了所有注解,需要注意里面有很多已經標記為Deprecated表明已經棄用了,
比如下面這段代碼,只是輸出value到終端,即使test()傳入null也不會導致空指標,Spotbugs本來不會發出警告,但是由于我們在方法上加了注解edu.umd.cs.findbugs.annotations.NonNull,Spotbugs會按照我們的意圖進行入參不允許為null的校驗,從而發出警告,
import edu.umd.cs.findbugs.annotations.NonNull;
public class SpotbugsAnnotationsSample {
public static void main(String[] args) {
test(null);
}
public static void test(@NonNull Integer value) {
// 輸出到終端
System.out.println(value);
}
}
下面是引入這個依賴的例子,參考Refer the version in the build script,這里面還提到從spotbugs v4版本開始,spotbugs.toolVersion 由 String 變為 Provider<String>,所以請使用 get() 或其他方式參考實際版本,
dependencies {
compileOnly "com.github.spotbugs:spotbugs-annotations:${spotbugs.toolVersion.get()}"
}
SpotBugs Gradle擴展屬性
includeFilter和excludeFilter
過濾器(Filter file)檔案可以定義匹配檢測項、被檢查的類和被檢查方法的一套匹配規則,讓我們可以為專案做定制化,檔案配置好后,使用SpotBugsTask提供的屬性指定過濾器檔案的路徑,實作包含(includeFilter)或者排除(excludeFilter)匹配的內容,
檔案是xml格式的,每個匹配規則單獨寫在<Match></Match>中,使用Types of Match clauses描述的各種標簽組合成匹配規則的內容,在Examples中給出了很多例子作為參考,
我們重點關注下category、code、pattern來指定Bug descriptions中列出來的檢查項,多個引數用逗號分隔,也可以使用正則運算式,以~字符開頭,
每個檢查項有唯一的pattern,比如下圖中的XSS_REQUEST_PARAMETER_TO_SEND_ERROR和XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER;多個檢查項可能屬于同一個code,比如下圖中的XSS;多個不同的code可能屬于同一個category,這三者之間是一個清晰的層級關系,這樣就可以按不同的粒度來配置,
下面給出了一個使用<Bug>簡單的例子和描述,更多例子請參考Examples,
<!--匹配指定的這兩個檢查項-->
<Match>
<Bug pattern="XSS_REQUEST_PARAMETER_TO_SEND_ERROR,XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER" />
</Match>
<!--匹配所有code為XSS的檢查項-->
<Match>
<Bug code="XSS" />
</Match>
<!--匹配SECURITY目錄下所有檢查項-->
<Match>
<Bug category="SECURITY" />
</Match>
visitors和omitVisitors
這兩個屬性可以分別指定使用(visitors)和禁用(omitVisitors)檢查器,一個檢查器會包含一個或者多個Bug descriptions中提到的檢查項,所以這兩個屬性配置的目的和includeFilter和excludeFilter是一樣的,讓我們可以為專案做定制化,只是從檢查器的維度進行配置,
在Detectors中將Spotbugs所有的檢查器都列出來了,在不配置的情況下,Standard detectors中列出來的默認使用,Disabled detectors中列出來的默認禁用,
以檢查器SynchronizationOnSharedBuiltinConstant為例,從下圖我們可以看到,檢查器名稱下面有段簡短的描述,再往下將檢查器包含的檢查項都列出來了,可以看到上文提到的pattern和code,點擊可以跳轉到Filter file檔案相應的位置,我們配置visitors和omitVisitors的時候填檢查器的名字SynchronizationOnSharedBuiltinConstant即可,

effort
effort是配置代碼檢測預期的級別,級別由低到高分別為min、less、more、max,級別越高計算成本越高,花費的時間也就越長,在這個檔案Effort里面有表格清晰的列出了這幾個級別分別包含了哪些檢查內容,effort的默認值是default,等同于more,
jvmArgs
jvmArgs用于設定JVM引數,因為SpotBugs是Java寫的,自然要在JVM上運行,我們在例子里面看到了-Duser.language=ja,這個意思是設定語言為日語,也就是代碼分析的結果展示的語音(輸出到終端或者報告中),總共有英語(en 默認),日語(ja),法語(fr)三種,在GitHub中可以看到相關展示文本的組態檔,

maxHeapSize
maxHeapSize是設定JVM最大堆記憶體大小,在spotbugsextension#maxHeapSizea中說了默認值為空,因此會使用Gradle的默認配置,所以一般不用管,
onlyAnalyze
onlyAnalyze指定哪些代碼要被SpotBugs分析,在大型專案里面用這個屬性避免沒必要的分析,可能會大大減少運行分析所需的時間,可以指定類名,或者包名,指定包名的時候用.*和.-的作用一樣,意思是分析這個包下以及子包中的檔案,
onlyAnalyze = ['com.foobar.MyClass', 'com.foobar.mypkg.*']
reportLevel
SpotBugs按嚴重程度高到低將Bug分為了三個等級P1、P2和P3,reportLevel屬性指明達到哪個等級的Bug才需要展示在報告里面,它可配置值對應有HIGH、MEDIUM、LOW和DEFAULT,它們定義在Confidence.groovy中,默認值是DEFAULT等同于MEDIUM,意思是要達到P2級別,那就意味著低級別的P3 Bug將被忽略,
reports
reports配置報告的型別,有html、xml、sarif和text四種,配置在SpotBugsTask中(比如spotbugsMain {}),再往里一層可配置的屬性不是很多,參考SpotBugsReport,下面是html型別報告的配置示例:
spotbugsMain {
reports {
html {
required = true
outputLocation = file("$buildDir/reports/spotbugs/main/spotbugs.html")
stylesheet = 'fancy-hist.xsl'
}
}
}
最佳實踐
配置
在根目錄gradle.properties中配置版本,
spotbugsGradlePluginVersion=5.0.13
findsecbugsPluginVersion=1.12.0
在根目錄build.gradle中增加以下配置:
buildscript {
repositories {
mavenLocal()
maven {
url "https://plugins.gradle.org/m2/"
}
mavenCentral()
}
dependencies {
classpath "com.github.spotbugs.snom:spotbugs-gradle-plugin:${spotbugsGradlePlugin}"
}
}
apply plugin: "com.github.spotbugs"
repositories {
mavenLocal()
maven {
url "https://plugins.gradle.org/m2/"
}
mavenCentral()
}
dependencies {
compileOnly "com.github.spotbugs:spotbugs-annotations:${spotbugs.toolVersion.get()}"
spotbugsPlugins "com.h3xstream.findsecbugs:findsecbugs-plugin:${findsecbugsPluginVersion}"
}
spotbugs {
ignoreFailures = false
showStackTraces = false
showProgress = false
excludeFilter = file("${project.rootDir}/code-analysis/spotbugs/exclude-filter.xml")
extraArgs = [ '-nested:false' ]
}
spotbugsMain {
reports {
html {
required = true
stylesheet = 'fancy-hist.xsl'
}
}
}
如果是多模塊專案按這種方式配置:
buildscript {
repositories {
mavenLocal()
maven {
url "https://plugins.gradle.org/m2/"
}
mavenCentral()
}
dependencies {
classpath "com.github.spotbugs.snom:spotbugs-gradle-plugin:${spotbugsGradlePlugin}"
}
}
allprojects {
apply plugin: "com.github.spotbugs"
repositories {
mavenLocal()
maven {
url "https://plugins.gradle.org/m2/"
}
mavenCentral()
}
dependencies {
compileOnly "com.github.spotbugs:spotbugs-annotations:${spotbugs.toolVersion.get()}"
spotbugsPlugins "com.h3xstream.findsecbugs:findsecbugs-plugin:${findsecbugsPluginVersion}"
}
spotbugs {
ignoreFailures = false
showStackTraces = false
showProgress = false
excludeFilter = file("${project.rootDir}/code-analysis/spotbugs/exclude-filter.xml")
extraArgs = ['-nested:false']
}
spotbugsMain {
reports {
html {
required = true
stylesheet = 'fancy-hist.xsl'
}
}
}
}
在專案根目錄下創建排除檢查項的檔案/code-analysis/spotbugs/exclude-filter.xml,后期再根據需要配置,
<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter
xmlns="https://github.com/spotbugs/filter/3.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://github.com/spotbugs/filter/3.0.0 https://raw.githubusercontent.com/spotbugs/spotbugs/3.1.0/spotbugs/etc/findbugsfilter.xsd">
</FindBugsFilter>
使用
在Gradle視窗中雙擊運行spotbugsMain任務即可,檢測完成會在Run視窗中列印出報告地址,
也可以在Terminal視窗中執行./gradlew spotbugsMain,可能需要先執行chmod +x gradlew給gradlew檔案執行權限,

如果執行程序中發生類似下面這種例外可以不用管,只是有部分相關的分析會無法執行,并不會中斷整個程序,其他不相關的部分都會正常檢查完成,在GitHub上issues#527很多人反映了這個問題,但是暫時沒有完美的解決,
The following classes needed for analysis were missing:
apply
test
accept
解讀報告
報告概要(Summary)按包和BUG等級統計了數量,

按目錄瀏覽(Browse by Categories)將發現的缺陷代碼按檢查項中的category、code、pattern分層展示,

按包名瀏覽(Browse by Packages)就是換了個角度,按照包名 > 類名 > 檢查項pattern分層展示,

最后一個視窗Info展示分析的代碼檔案(Analyzed Files)、分析的源檔案夾(Source Files)使用的依賴(Used Libraries)、使用到的SpotBugs插件(Plugins)和分析中產生的例外(Analysis Errors),
過濾配置
通過includeFilter和excludeFilter指定過濾器(Filter file)檔案是最靈活的,基本什么維度都可以控制,但是建議這里面只配置要包含或者排除哪些檢查項,使用category、code、pattern配置不同的粒度,
從整體縮小被檢查的代碼范圍使用onlyAnalyze,如果有必要的話,如果要忽略不檢查具體的類或者方法可以使用注解@SuppressFBWarnings來標記,它來自spotbugs-annotations,
其他技巧
SpotBugs Links里面列出了跟SpotBugs集成或者相似的工具,有需要可以了解下,
參考
[SpotBugs]官網
[SpotBugs]官方檔案
[SpotBugs]SpotBugsTask
[SpotBugs]SpotBugsExtension
[Gradle]spotbugs
[GitHub]SpotBugs
[GitHub]FindBugs
[GitHub]spotbugs-gradle-plugin
[FindBugs]官網
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/549026.html
標籤:其他
上一篇:java筆記(this,super,override,instanceof,static)
下一篇:Java筆記(8) 例外和錯誤
