1. Overview

Identifying bugs in Java programs is a critical challenge in software development. SpotBugs is an open-source static analysis tool used to find bugs in Java code. It operates on Java bytecode, rather than source code to identify potential issues in code, such as bugs, performance issues, or bad practices. SpotBugs is the successor to FindBugs and builds upon its capabilities, offering more detailed and precise bug detection. In this article, well explore how to set up SpotBugs on a Java project and integrate it into the IDE and the Maven build.

2. Bug Patterns

SpotBugs checks more than 400 bug patterns such as null pointer dereferencing, infinite recursive loops, bad uses of the Java libraries, and deadlocks. In SpotBugs, bug patterns are classified by means of several variables, such as the type of violation, its category, the rank of the bug, and the confidence of the discovering process. SpotBugs has ten bug patterns categories:

  • Bad Practice: Detects bad coding practices that might not cause immediate problems but could lead to issues in the future. Examples include hash code and equals problems, cloneable idiom, dropped exceptions, Serializable problems, and misuse of finalize.
  • Correctness: Identifies code that is likely to be incorrect and might lead to runtime errors such as a probable bug.
  • Experimental: Refers to bug patterns that are relatively new, experimental, or not fully validated.
  • Internationalization: Detects potential issues in Java code related to internationalization and locale.
  • Malicious Code Vulnerability: Flags code that could be exploited by an attacker.
  • Multithreaded Correctness: Checks for potential issues in multi-threaded code, such as race conditions and deadlocks.
  • Bogus Random Noise: Intended to be useful as a control in data mining experiments, not in finding actual bugs in software.
  • Performance: Identifies code that isn’t necessarily incorrect but may be inefficient.
  • Security: Highlights security vulnerabilities in the code.
  • Dodgy Code: Looks for code that isn’t necessarily incorrect but suspicious and potentially problematic. Code that is confusing, anomalous, or written in a way that leads itself to errors. Examples include dead local stores, switch fall through, unconfirmed casts, and redundant null check of value known to be null.

One of the features of SpotBugs is the ability to categorize bugs into different severity ranks. SpotBugs ranks bugs on a numeric scale from 1 to 20, with the ranking indicating the severity of the issue. The numeric rankings can be categorized as follows:

  • Scariest (High Priority): Ranks 1 to 4
  • Scary (Medium Priority): Ranks 5 to 9
  • Troubling (Low Priority): Ranks 10 to 14
  • Of Concern (Informational): Ranks 15 to 20

3. SpotBugs Maven Plugin

Spotbugs can be used as a standalone application, as well as through several integrations including Maven, Gradle, Eclipse, and IntelliJ. In this section, we’re focusing on Maven integration.

3.1. Maven Configuration

Let’s start by importing the spotbugs**-maven-plugin plugin in the section of the pom.xml:

<plugin>
    <groupId>com.github.spotbugs</groupId>
    <artifactId>spotbugs-maven-plugin</artifactId>
    <version>4.8.5.0</version>
    <dependencies>
        <dependency>
        <groupId>com.github.spotbugs</groupId>
            <artifactId>spotbugs</artifactId>
        <version>4.8.5</version>
        </dependency>
    </dependencies>
</plugin>

3.2. Generating the Report

Once the plugin has been added, we can open a terminal and run the following command:

mvn spotbugs:check

This runs an analysis of our source code and then outputs a list of warnings that we need to fix. To generate a bug report we need some code to work with. To keep things simple, we’ll be using the project available on GitHub. Let’s assume that we’re using the following class:

public class Application {

    public static final String NAME = "Name: ";

    private Application() {
    }

    public static String readName() {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.next();
        return NAME.concat(input);
    }
}

Now, we can run the mvn spotbugs:check command. The following was detected when it was run at one point:

[INFO] BugInstance size is 1
[INFO] Error size is 0
[INFO] Total bugs: 1
[ERROR] High: Found reliance on default encoding in com.baeldung.systemin.Application.readName(): new java.util.Scanner(InputStream) [com.baeldung.systemin.Application] At Application.java:[line 13] DM_DEFAULT_ENCODING

From this report, we can see that our Application class has one bug with high priority.

3.3. Viewing the Result

SpotBugs generates a report in an XML format in target/spotbugsXml.xml. To have a prettier report, we need to add htmlOutput configuration in the SpotBugs plugin:

<configuration>
    <htmlOutput>true</htmlOutput>
</configuration>

Now, we run the mvn clean install and mvn spotbugs:check commands. Then, we navigate to the target/spotbugs.html and open the file to see the results directly in a browser:   spotbugs html Also, we can see bug details using the Spotbugs GUI using the Maven command mvn spotbugs:gui:   spotbugs 1 With this feedback, we can now update our code to fix the bug proactively.

3.4. Fixing Bugs

Our Application class has the DM_DEFAULT_ENCODING bug. The bug indicates the use of the default character encoding when performing I/O operations. This can lead to unexpected behavior if the default encoding varies across different environments or platforms. By explicitly specifying the character encoding, we ensure consistent behavior regardless of the platform’s default encoding. To fix this, we can add StandardCharsets to the Scanner class:

public static String readName() {
    Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.displayName());
    String input = scanner.next();
    return NAME.concat(input);
}

After adding the previously suggested change, running mvn spotbugs:check again produces a bugs-free report:

[INFO] BugInstance size is 0
[INFO] Error size is 0
[INFO] No errors/warnings found

4. SpotBugs IntelliJ IDEA Plugin

IntelliJ SpotBugs plugin provides static byte code analysis to look for bugs in Java code from within IntelliJ IDEA. The plugin uses SpotBugs under the hood.

4.1. Installation

To install the SpotBugs plugin in IntelliJ IDEA, we open the application and navigate to “Welcome Screen“. If a project is open, we go to “File -> Settings” (or “IntelliJ IDEA -> Preferences” on macOS). In the settings window, we select “Plugins” and then go to the “Marketplace” tab. Using the search bar, we find “SpotBugs” and, once located, click the “Install” button. After the installation completes, we restart IntelliJ IDEA to activate the plugin:   spotbugs intellij For a manual installation of the SpotBugs plugin, we first download the plugin from the JetBrains Plugin Repository. After downloading the plugin zip file, we open IntelliJ IDEA and navigate to the “Welcome Screen“, then go to “File > Settings“. In the settings window, we select “Plugins“, click on the “Gear Icon” in the top right corner, and choose “Install Plugin from Disk“. We then navigate to the location where we downloaded the SpotBugs plugin zip file, select it, and click “OK“. Finally, we restart IntelliJ IDEA to activate the plugin.

4.2. Reports Browsing

In order to launch static analysis in IDEA, we can click on “Analyze Current File” in the SpotBugs-IDEA panel and then inspect the results:   spotbugs intellij usage We can use the second column of commands on the left side of the screenshot to group bugs by various factors, such as bug category, class, package, priority, or bug rank. It’s also possible to export the reports in XML/HTML format, by clicking the “export” button in the third column of commands.

4.3. Configuration

The SpotBugs plugin for IntelliJ IDEA offers various preferences and settings that allow users to customize the analysis process and manage how bugs are reported. The below figure shows the SpotBugs plugin preferences:   spotbugs intellij config Here’s an overview of the typical preferences available in the SpotBugs plugin:

  • Bug Categories and Priorities: We can configure which categories of bugs we want SpotBugs to detect. We can also set the minimum rank for bug detection, allowing us to focus on more critical issues.
  • Filter Files: This tab allows us to manage which parts of the codebase are included or excluded from analysis. We can define patterns to exclude or include specific packages, classes, or methods from the analysis.
  • Annotations: The plugin supports configuring annotations for classes, methods, and fields. These annotations can be used to suppress specific warnings or to provide additional information to SpotBugs.
  • Detector: It provides settings related to the detection mechanisms used by SpotBugs. We can enable or disable specific bug detectors based on our needs. For example, one can focus on security issues by enabling security-related detectors and disabling others.

These preferences and settings provide flexibility and control over how SpotBugs analyzes the code and reports potential issues, helping developers maintain high code quality and address bugs effectively.

5. SpotBugs Eclipse Plugin

In this section, we focus on the SpotBugs Eclipse Plugin, delving into its installation process, and usage within the Eclipse IDE.

5.1. Installation

We begin by launching Eclipse IDE and navigating to the “Help” in the menu bar. After that, we select “Eclipse Marketplace“. In the Marketplace window, we type “SpotBugs” into the search box and press “Enter“. When the search results appear, we find SpotBugs and click on the “Install” button next to it. We follow the installation wizard to complete the installation process. Finally, we restart Eclipse to activate the plugin:   spotbugs eclipse Alternatively, if SpotBugs isn’t available in “Eclipse Marketplace” or if we prefer to install it via the update site, we can open Eclipse and go to the “Help” menu at the top. From the dropdown menu, we select “Install New Software” and then click on the “Add” button in the dialog that appears. In the “Add Repository” dialog, we enter a name for the repository, such as “SpotBugs“, and input the https://spotbugs.github.io/eclipse URL in the “Location” field. After clicking “OK“, we check the box next to “SpotBugs” in the list of available software, click “Next“, and follow the prompts to complete the installation. Finally, we restart Eclipse to activate the plugin.

5.2. Reports Browsing

To launch a static analysis on a project using the SpotBugs Eclipse plugin, we need to right-click the project in the “Project Explorer“, and then navigate to “SpotBugs -> Find Bugs“. After that, Eclipse shows the results under the “Bug Explorer” window.

5.3. Configuration

We can check the configuration interface by going to “Window -> Preferences -> Java -> SpotBugs“:   spotbugs eclipse setting We can freely uncheck unwanted categories, raise the minimum rank to report, specify the minimum confidence to report, and customize markers for bug ranks. Under the “Detector configuration” tab, the Eclipse SpotBugs plugin allows us to customize which bug detectors are enabled or disabled. This tab provides a detailed list of available detectors, each designed to identify specific types of potential issues in the code. Under the “Filter files” panel, we can create custom file filters, allowing us to include or exclude specific files or directories from the SpotBugs analysis. This feature enables fine-tuned control over which parts of the codebase are analyzed, ensuring that irrelevant or non-essential files aren’t included in the bug detection process.

6. Conclusion

In this article, we’ve discussed the basic key points to using SpotBugs in a Java project. SpotBugs is a static analysis tool that helps identify potential bugs in our code by examining bytecode. We learned how to configure SpotBugs with Maven, a widely used build automation tool in the Java ecosystem, to automate the detection of issues during the build process. Additionally, we walked through the process of integrating SpotBugs into popular development environments, including IntelliJ IDEA and Eclipse, ensuring that we can easily incorporate bug detection into our workflow. As always, the full source code is available over on GitHub.