How to use SpotBugs in your Java projects
When you start a new Java project or even if you already have one, it is a good practice to keep that codebase away from bugs. There are several alternatives to keep your code clean like Checkstyle [3], which is focused on keeping coding standards, PMD [4] or FindBugs [5], which is the discontinued predecessor of SpotBugs1, the tool I am going to present within this post.
SpotBugs, as PMD, is a software which uses static analysis [6] to find bugs in Java code. It is free and distributed under GNU Lesser General Public License.
SpotBugs checks for more than 400 bug patterns [4].
SpotBugs can analyze compiled programs for any version of Java, from 1.0 to 1.9, although it requires JRE or JDK 1.8.0 or later to run. It can be also integrated with popular IDEs like IntelliJ, Eclipse or Visual Studio Code. It can be used as a standalone program or integrated as a plugin in Ant, Maven or Gradle. In this post I’ll write on how to configure it as a Maven plugin.
The following is the minimal configuration to add the SpotBugs plugin to the
pom.xml
file:
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>4.1.3</version>
<dependencies>
<dependency>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs</artifactId>
<version>4.2.0</version>
</dependency>
</dependencies>
</plugin>
The SpotBugs plugin has three main goals:
spotbugs:spotbugs
: it analyses target projectspotbugs:check
: the same asspotbugs:spotbugs
but it makes the build failed if it finds any bugspotbugs:gui
: it launches the GUI
Run maven spotbugs:check
to check your project from command line.
To include the SpotBug’s goal into your Maven pipeline, just add it to any of
your phases, typically compile
, as we can see here:
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>4.1.4</version>
<configuration>
<xmlOutput>true</xmlOutput>
<!-- Optional directory to put spotbugs xdoc xml report -->
<xmlOutputDirectory>target/site</xmlOutputDirectory>
</configuration>
<executions>
<execution>
<id>default-report</id>
<phase>verify</phase> <!-- this the default phase -->
<goals>
<!-- Replace with spotbugs to not fail the build -->
<goal>check</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs</artifactId>
<version>4.1.4</version>
</dependency>
</dependencies>
</plugin>