StackPractices
intermediate By Mathias Paulenko

Detect Bugs in Java with SpotBugs Static Analysis

How to configure SpotBugs for Maven and Gradle, interpret bug patterns, suppress false positives, and integrate with CI/CD pipelines.

Topics: security

Overview

SpotBugs analyzes compiled Java bytecode and reports bug patterns — null pointer dereferences, resource leaks, SQL injection, unsafe serialization, and concurrency issues. It’s the community-maintained successor to FindBugs, plugs into Maven, Gradle, and every major IDE, and the Find Security Bugs plugin adds a dedicated security rule set on top. Every finding carries a rank (1–20) and a coarse priority (High, Medium, Low), so a CI gate can fail on what actually matters instead of drowning in style noise.

When to Use

  • Java projects where a null dereference or resource leak in production costs more than a slow CI job
  • Codebases handling user input, file I/O, or database calls — the classes of bugs SpotBugs was built for
  • Pull request pipelines that should reject new bug patterns before merge
  • Security audits of Java applications, with the Find Security Bugs plugin enabled
  • Teams standardizing code quality across several repositories; for Python, Bandit plays the same role

When NOT to Use

  • Non-JVM languages — SpotBugs only analyzes Java bytecode
  • Kotlin or Scala projects — use Detekt or Scalafix instead; SpotBugs’ rules assume Java idioms
  • When you need runtime behavior (memory, CPU, latency) — that’s profiling, not static analysis
  • For dependency vulnerability scanning — use OWASP Dependency-Check or, in Python, pip-audit

Solution

Maven configuration

<!-- pom.xml -->
<build>
  <plugins>
    <plugin>
      <groupId>com.github.spotbugs</groupId>
      <artifactId>spotbugs-maven-plugin</artifactId>
      <version>4.9.3.0</version>
      <dependencies>
        <dependency>
          <groupId>com.github.spotbugs</groupId>
          <artifactId>spotbugs</artifactId>
          <version>4.9.3</version>
        </dependency>
      </dependencies>
      <configuration>
        <effort>Max</effort>
        <threshold>Medium</threshold>
        <failOnError>true</failOnError>
        <excludeFilterFile>spotbugs-exclude.xml</excludeFilterFile>
        <plugins>
          <plugin>
            <groupId>com.h3xstream.findsecbugs</groupId>
            <artifactId>findsecbugs-plugin</artifactId>
            <version>1.14.0</version>
          </plugin>
        </plugins>
      </configuration>
      <executions>
        <execution>
          <goals>
            <goal>check</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

The check goal runs the analysis itself and then fails the build if anything above the threshold is found — no separate spotbugs:spotbugs execution needed. Note that failOnError defaults to true, which is why an unconfigured run on an old codebase often goes red on the first scan.

Gradle configuration

// build.gradle
plugins {
  id 'com.github.spotbugs' version '6.5.13'
}

spotbugs {
  effort = 'max'
  reportLevel = 'medium'
  excludeFilter = file('spotbugs-exclude.xml')
}

spotbugsMain {
  reports {
    html {
      required = true
      outputLocation = file("$buildDir/reports/spotbugs/main/spotbugs.html")
    }
    xml {
      required = true
      outputLocation = file("$buildDir/reports/spotbugs/main/spotbugs.xml")
    }
  }
}

// Add Find Security Bugs plugin
dependencies {
  spotbugsPlugins 'com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0'
}

Gradle Kotlin DSL

// build.gradle.kts
plugins {
    id("com.github.spotbugs") version "6.5.13"
}

spotbugs {
    effort = com.github.spotbugs.snom.Effort.MAX
    reportLevel = com.github.spotbugs.snom.Confidence.MEDIUM
    excludeFilter = file("spotbugs-exclude.xml")
}

spotbugsMain {
    reports {
        create("html") {
            required = true
            outputLocation = file("$buildDir/reports/spotbugs/main/spotbugs.html")
        }
        create("xml") {
            required = true
            outputLocation = file("$buildDir/reports/spotbugs/main/spotbugs.xml")
        }
    }
}

dependencies {
    spotbugsPlugins("com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0")
}

Running SpotBugs

# Maven
mvn spotbugs:check

# Maven with a stricter threshold
mvn spotbugs:check -Dspotbugs.threshold=high

# Gradle
./gradlew spotbugsMain

# Gradle — check all source sets
./gradlew spotbugsMain spotbugsTest

# Generate the report without failing the build
mvn spotbugs:spotbugs

Exclude filter file

<!-- spotbugs-exclude.xml -->
<FindBugsFilter>
  <!-- Exclude test classes -->
  <Match>
    <Class name="~.*Test"/>
  </Match>

  <!-- Exclude generated code -->
  <Match>
    <Class name="~.*Generated.*"/>
  </Match>

  <!-- Exclude a bug pattern in one class -->
  <Match>
    <Class name="com.example.legacy.LegacyService"/>
    <Bug pattern="EI_EXPOSE_REP"/>
  </Match>

  <!-- Exclude a bug pattern everywhere -->
  <Match>
    <Bug pattern="EI_EXPOSE_REP,EI_EXPOSE_REP2"/>
  </Match>

  <!-- Exclude by priority and category -->
  <Match>
    <Bug category="PERFORMANCE" priority="3"/>
  </Match>
</FindBugsFilter>

Common SpotBugs findings and fixes

NP_NULL_ON_SOME_PATH — Possible null pointer dereference

// BAD — SpotBugs: NP_NULL_ON_SOME_PATH
public String getUserName(User user) {
    return user.getName().trim();  // user could be null
}

// GOOD — null check
public String getUserName(User user) {
    if (user == null) {
        return "";
    }
    return user.getName().trim();
}

// GOOD — use Optional
public String getUserName(Optional<User> user) {
    return user.map(User::getName).map(String::trim).orElse("");
}

EI_EXPOSE_REP — Returning internal array exposes representation

// BAD — SpotBugs: EI_EXPOSE_REP
public class Inventory {
    private String[] items;

    public String[] getItems() {
        return items;  // Exposes the internal array to modification
    }
}

// GOOD — return a copy
public class Inventory {
    private String[] items;

    public String[] getItems() {
        return Arrays.copyOf(items, items.length);
    }

    // Or return an unmodifiable list
    public List<String> getItemList() {
        return Collections.unmodifiableList(Arrays.asList(items));
    }
}

MS_SHOULD_BE_FINAL — Field should be final

// BAD — SpotBugs: MS_SHOULD_BE_FINAL
public class Config {
    public static String API_URL = "https://api.example.com";
}

// GOOD — make it final
public class Config {
    public static final String API_URL = "https://api.example.com";
}

SQL_INJECTION_JDBC — Potential SQL injection

// BAD — SpotBugs: SQL_INJECTION_JDBC (Find Security Bugs)
public User findUser(String name) throws SQLException {
    String query = "SELECT * FROM users WHERE name = '" + name + "'";
    Statement stmt = connection.createStatement();
    ResultSet rs = stmt.executeQuery(query);
    // ...
}

// GOOD — use PreparedStatement
public User findUser(String name) throws SQLException {
    String query = "SELECT * FROM users WHERE name = ?";
    PreparedStatement stmt = connection.prepareStatement(query);
    stmt.setString(1, name);
    ResultSet rs = stmt.executeQuery();
    // ...
}

OBL_UNSATISFIED_OBLIGATION — Resource not closed on all paths

// BAD — SpotBugs: OBL_UNSATISFIED_OBLIGATION
public String readFile(String path) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(path));
    String line = reader.readLine();
    return line;  // reader never closed
}

// GOOD — try-with-resources
public String readFile(String path) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
        return reader.readLine();
    }
}

RCN_REDUNDANT_NULLCHECK — Redundant null check

// BAD — SpotBugs: RCN_REDUNDANT_NULLCHECK
public void process(String input) {
    if (input != null) {
        String result = input.trim();
        if (result != null) {  // trim() never returns null
            System.out.println(result);
        }
    }
}

// GOOD — remove the redundant check
public void process(String input) {
    if (input != null) {
        String result = input.trim();
        System.out.println(result);
    }
}

Inline suppression with annotations

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

public class LegacyService {

    @SuppressFBWarnings(
        value = "EI_EXPOSE_REP",
        justification = "Internal API, not exposed to untrusted callers"
    )
    public String[] getInternalData() {
        return items;
    }

    // Suppress multiple patterns
    @SuppressFBWarnings(
        value = {"NP_NULL_ON_SOME_PATH", "RCN_REDUNDANT_NULLCHECK"},
        justification = "Reviewed: input is validated upstream"
    )
    public void process(String input) {
        // ...
    }
}

CI/CD integration with GitHub Actions

# .github/workflows/spotbugs.yml
name: SpotBugs Analysis

on: [push, pull_request]

jobs:
  spotbugs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'
          cache: maven

      - name: Run SpotBugs
        run: mvn spotbugs:check -Dspotbugs.threshold=medium

      - name: Generate report
        if: always()
        run: mvn spotbugs:spotbugs

      - name: Upload report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: spotbugs-report
          path: target/spotbugsXml.xml

CI/CD with Gradle

# .github/workflows/spotbugs-gradle.yml
name: SpotBugs Analysis

on: [push, pull_request]

jobs:
  spotbugs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'

      - name: Run SpotBugs
        run: ./gradlew spotbugsMain --continue

      - name: Upload report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: spotbugs-report
          path: build/reports/spotbugs/

If several modules share the same gate, extracting this job into a reusable GitHub Actions workflow keeps the threshold, Java version, and artifact upload in one place.

Find Security Bugs plugin

The findsecbugs-plugin dependency shown in the Maven and Gradle configs is what turns SpotBugs into a security scanner. It contributes detectors for SQL injection, XSS, LDAP injection, path traversal, insecure deserialization, weak cryptography, hardcoded passwords, and suspicious file permissions — most of the SECURITY-category findings come from it, not from SpotBugs core.

Explanation

SpotBugs never looks at your .java sources. It walks the compiled .class bytecode and matches it against a database of several hundred bug patterns, which is why the analysis goal binds after compile — and also why it can flag code you didn’t write, like Lombok-generated methods or shaded dependencies. The exclude filter exists largely for those cases.

Java source is compiled to bytecode, SpotBugs classifies findings and writes a report; CI fails when new findings cross the gate.

How findings are classified

Each finding carries a rank from 1 to 20 — lower is scarier: ranks 1–4 are “scariest”, 5–9 “scary”, 10–14 “troubling”, and 15–20 “of concern” — plus a confidence describing how sure the detector is. The Maven threshold and Gradle reportLevel settings filter on the coarse High/Medium/Low priority derived from these values. That’s why Medium is the sensible default: High hides real bugs behind low-confidence filters, and Low floods the report with maybes.

Every pattern also belongs to a category. The ones that matter day to day are CORRECTNESS (probable bugs), BAD_PRACTICE (code that works but invites trouble), MALICIOUS_CODE (mutability and encapsulation leaks like EI_EXPOSE_REP), SECURITY (mostly from Find Security Bugs), PERFORMANCE, and MT_CORRECTNESS (concurrency). Filtering on category is the clean way to build a security-only gate without lowering the global threshold.

PatternCategoryWhat it catches
NP_NULL_ON_SOME_PATHCORRECTNESSA reference that’s null on one path gets dereferenced
EI_EXPOSE_REP / EI_EXPOSE_REP2MALICIOUS_CODEMutable internal state leaking out (or in) through getters and constructors
MS_SHOULD_BE_FINALBAD_PRACTICEA static field that never changes but isn’t final
SQL_INJECTION_JDBCSECURITYUser input concatenated into a JDBC query — from Find Security Bugs
OBL_UNSATISFIED_OBLIGATIONCORRECTNESSA stream or connection not closed on every path
RCN_REDUNDANT_NULLCHECKCORRECTNESSNull-checking a value that provably can’t be null

Reading the report

Maven writes target/spotbugsXml.xml plus a site report; Gradle writes whichever formats you enable under build/reports/spotbugs/. For a first pass on a large codebase, mvn spotbugs:gui opens a viewer that groups findings by class, category, and rank — much faster triage than scrolling through XML. For pipelines, -Dspotbugs.sarifOutput=true emits SARIF, which GitHub code scanning and several PR-review bots ingest directly (see Variants).

Rolling it out on a legacy codebase

Switching failOnError on against a codebase that was never scanned typically yields hundreds of findings and an instant red build. The rollout that survives contact with a real project looks like this: run mvn spotbugs:spotbugs once, keep the generated spotbugsXml.xml as spotbugs-baseline.xml, and from then on check with -Dspotbugs.excludeBugsFile=spotbugs-baseline.xml. Anything already in the baseline file is suppressed, so only newly introduced bugs can break the build. Burn the baseline down file by file until it’s empty, then drop the flag.

Where SpotBugs sits among Java analyzers

SpotBugs isn’t the only static analyzer in the Java world, and it doesn’t try to cover everything:

ToolWhat it analyzesWhere it’s strongest
SpotBugsCompiled .class bytecodeProbable-bug patterns — null derefs, resource leaks, concurrency — plus security via Find Security Bugs
PMDSource codeRule-based bug-prone patterns and style; its CPD module also hunts copy-paste
CheckstyleSource codeConventions only — naming, Javadoc, layout; it never claims to find bugs
Error ProneInside javacGoogle’s compile-time bug checks that fail the build on known API misuse

They overlap less than you’d expect: Error Prone runs during compilation, SpotBugs afterward in CI, and Checkstyle covers style — combining them is additive, not redundant. PMD is the closest alternative on correctness rules.

Variants

SpotBugs with a custom ruleset

<!-- spotbugs-include.xml — run only specific categories -->
<FindBugsFilter>
  <Match>
    <Bug category="SECURITY,CORRECTNESS,MALICIOUS_CODE"/>
  </Match>
</FindBugsFilter>
<!-- pom.xml -->
<configuration>
  <includeFilterFile>spotbugs-include.xml</includeFilterFile>
  <excludeFilterFile>spotbugs-exclude.xml</excludeFilterFile>
</configuration>

SpotBugs inside SonarQube

SonarQube’s own Java analyzer already covers part of what SpotBugs reports, and the community sonar-findbugs plugin imports SpotBugs and Find Security Bugs results into the SonarQube dashboard. There’s no -D flag for this on the scanner side — the plugin is installed on the SonarQube server, after which mvn sonar:sonar picks up the SpotBugs findings during analysis. If you only need a CI gate and not a dashboard, plain spotbugs:check is the simpler setup.

SARIF output for GitHub code scanning

# .github/workflows/spotbugs-sarif.yml — report shows up in the Security tab
- name: Run SpotBugs with SARIF output
  run: mvn spotbugs:spotbugs -Dspotbugs.sarifOutput=true -Dspotbugs.sarifOutputFilename=spotbugs.sarif

- name: Upload SARIF
  if: always()
  uses: github/codeql-action/upload-sarif@v3
  with:
    sarif_file: target/spotbugs.sarif

Baseline for incremental adoption

# Run once — the generated report becomes the baseline
mvn spotbugs:spotbugs
cp target/spotbugsXml.xml spotbugs-baseline.xml

# Subsequent runs report only bugs not in the baseline
mvn spotbugs:check -Dspotbugs.excludeBugsFile=spotbugs-baseline.xml

Best Practices

  • Use effort=Max for thorough analysis — slower, but it turns on extra detectors
  • Start with threshold=Medium — High misses real bugs, Low is mostly noise
  • Enable the Find Security Bugs plugin — the base patterns miss most security issues
  • Keep exclusions in a filter file — reviewed XML beats scattered annotations without justification
  • Run in CI/CD — catch bugs before merge, not in production
  • Always fill justification in @SuppressFBWarnings — the reason matters more than the suppression
  • Combine with JaCoCo for coverage — SpotBugs finds bugs, JaCoCo shows what is tested
  • Review excludes periodically — new SpotBugs versions add new patterns

Common Mistakes

  • Setting failOnError=true on legacy codebases: hundreds of findings will break the build. Start with false, fix gradually, then enable.
  • Suppressing without justification: a bare @SuppressFBWarnings tells the next reader nothing — the justification field is the actual point of the annotation.
  • Only running on the main source set: test code can have bugs too. Run spotbugsTest as well.
  • Ignoring Low priority findings: some Low findings flag patterns that escalate later. Review them periodically.
  • Not using Find Security Bugs: core SpotBugs won’t catch SQL injection, XSS, or unsafe deserialization — those detectors all live in the plugin.

See Also

Frequently Asked Questions

What is SpotBugs?

A bytecode analyzer for Java. It scans your compiled .class files against a few hundred known bug patterns — null dereferences, unclosed resources, SQL injection through the Find Security Bugs plugin, threading mistakes, and more.

How is SpotBugs different from FindBugs?

SpotBugs is the community-maintained successor to FindBugs, which is no longer maintained. Its runtime requirement and the bytecode versions it can analyze are separate and vary by release. The current SpotBugs documentation requires JRE 11 or later to run; check the compatibility notes for the version you pin.

What is Find Security Bugs?

A SpotBugs plugin that contributes security-specific bug patterns — SQL injection, XSS, path traversal, insecure deserialization, weak crypto, hardcoded passwords, and more.

What do SpotBugs rank and priority mean?

Each finding gets a rank between 1 and 20 — 1 is scariest, 20 is barely worth a look — plus a coarse High/Medium/Low priority derived from it. The threshold and reportLevel settings filter on that priority; Medium is the usual balance.

Should I use SpotBugs or SonarQube?

They complement each other. SpotBugs performs the deep bytecode analysis itself, while SonarQube is a dashboard that runs its own Java analyzer and can also ingest SpotBugs results through the sonar-findbugs plugin. Use SpotBugs for the CI gate, SonarQube for trends over time.

How do I suppress a SpotBugs finding?

Use @SuppressFBWarnings(value = "BUG_CODE", justification = "reason") on the method or class. For broader exclusions, use the XML exclude filter file; to grandfather an existing codebase, use the baseline file described in Variants.