Maven – SpotBugs example
In this article, we will show you how to use SpotBugs Maven Plugin to find bugs in Java code.
Findbugs is no longer maintained, and thus SpotBugs is the spiritual successor of FindBugs
P.S SpotBugs requires JDK 1.8
1. Maven SpotBugs Plugin
Define the spotbugs-maven-plugin
in the reporting
tag. So that mvn site
will generate the SpotBugs report.
<reporting>
<plugins>
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>3.1.8</version>
</plugin>
</plugins>
</reporting>
2. Java Code
A simple Java code, with an unused field ‘abc’ and a performance issue in the “+ string” loop. Later, SpotBugs will be able to detect it and showing it on the report.
package com.mkyong.examples;
public class StaticCodeExample {
//Unused field
private int abc;
private String ip = "127.0.0.1";
public void test() {
String[] field = {"a", "b", "c", "s", "e"};
//concatenates strings using + in a loop
String s = "";
for (int i = 0; i < field.length; ++i) {
s = s + field[i];
}
System.out.println(ip);
}
}
3. Maven Site
mvn compile site
to generate a Maven site for the Java project, the SpotBugs report will be generated and integrated into the Maven site automatically.
$ mvn compile site
[INFO] Generating "SpotBugs" report --- spotbugs-maven-plugin:3.1.8:spotbugs
[INFO] Generating "Dependency Information" report --- maven-project-info-reports-plugin:3.0.0:dependency-info
[INFO] Generating "About" report --- maven-project-info-reports-plugin:3.0.0:index
[INFO] Generating "Plugin Management" report --- maven-project-info-reports-plugin:3.0.0:plugin-management
[INFO] Generating "Plugins" report --- maven-project-info-reports-plugin:3.0.0:plugins
[INFO] Generating "Summary" report --- maven-project-info-reports-plugin:3.0.0:summary
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.732 s
[INFO] Finished at: 2018-11-19T15:38:56+08:00
[INFO] ------------------------------------------------------------------------
4. SpotBugs Report
Review the report at target/site/spotbugs.html
5. FAQs
5.1 Review the SpotBugs 400 bug patterns here.
5.2 More Maven SpotBugs Plugin recipes here
Download Source Code
$ git clone https://github.com/mkyong/maven-examples.git
$ cd maven-static-code-analysis
$ mvn compile site
# view report at target/site/spotbugs.html
hi i have doubt in spotbugs tool?
can we customize the report?
So… Is that project dead or what? All sources are deadlinked… https://mailman.cs.umd.edu/pipermail/findbugs-discuss/2016-November/004321.html
SpotBugs Now.
https://spotbugs.github.io/
hi sir,
can u please let me know any chance to customize the spotbug report?