Introduction to FindBugs – FindBugs简介

最后修改: 2016年 11月 5日


1. Overview


FindBugs is an open source tool used to perform static analysis on Java code.


In this article, we’re going to have a look at setting up FindBugs on a Java project and integrating it into the IDE and the Maven build.


2. FindBugs Maven Plugin

2.FindBugs Maven Plugin

2.1. Maven Configuration


In order to start generating static analysis reports, we first need to add the FindBugs plugin in our pom.xml:



You can check out the latest version of the plugin on Maven Central.


2.2. Report Generation


Now that we have the Maven plugin properly configured, let’s generate the project documentation using the mvn site command.

现在我们正确配置了Maven插件,让我们用mvn site命令生成项目文档。

The report will be generated in the folder target/site in the project directory under the name findbugs.html.


You can also run the mvn findbugs:gui command to launch the GUI interface to browse the generated reports for the current project.

你也可以运行mvn findbugs:gui命令来启动GUI界面,浏览当前项目的生成的报告。

The FindBugs plugin can also be configured to fail under some circumstances – by adding the execution goal check to our configuration:



The effort – when maxed out, performs a more complete and precise analysis, revealing more bugs in the code, though, it consumes more resources and takes more time to complete.


You can now run the command mvn verify, to check if the build will succeed or not – depending on the defects detected while running the analysis.

现在你可以运行mvn verify命令,检查构建是否会成功–取决于运行分析时检测到的缺陷。

You can also enhance the report generation process and take more control over the analysis, by adding some basic configuration to the plugin declaration:



The onlyAnalyze option declares a comma separated values of classes/packages eligible for analysis.


The visitors/omitVisitors options are also comma separated values, they are used to specify which detectors should/shouldn’t be run during the analysis – Note that visitors and omitVisitors cannot be used at the same time.

visitors/omitVisitors选项也是逗号分隔的值,它们被用来指定在分析过程中应该/不应该运行哪些检测器 – 注意,visitorsomitVisitors不能同时使用

A detector is specified by its class name, without any package qualification. Find the details of all detectors class names available by following this link.


3. FindBugs Eclipse Plugin

3.FindBugs Eclipse插件

3.1. Installation


The IDE installation of the FindBugs Plugin is pretty straightforward – you just need to use the software update feature in Eclipse, with the following update site:

FindBugs插件的IDE安装非常简单 – 你只需要使用Eclipse,中的软件更新功能,更新网站如下。

To make sure that FindBugs is properly installed in your Eclipse environment, then, look for the option labeled FindBugs under Windows -> Preferences -> Java.

要确保FindBugs已经正确地安装在你的Eclipse环境中,那么就在Windows -> Preferences -> Java下寻找标有FindBugs的选项。

3.2. Reports Browsing


In order to launch a static analysis on a project using the FindBugs Eclipse plugin, you need to right-click the project in the package explorer, then, click on the option labeled find bugs.

为了使用FindBugs Eclipse插件对一个项目进行静态分析,你需要在包资源管理器中右键单击该项目,然后,单击标有查找错误的选项。

After launch, Eclipse shows the results under the Bug Explorer window as shown in the screenshot below:

启动后,Eclipse在Bug Explorer窗口下显示结果,如下图所示。

bug explorer
As of version 2, FindBugs started ranking bugs with a scale from 1 to 20 to measure the severity of defects:

bug explorer

  • Scariest: ranked between 1 & 4.
  • Scary: ranked between 5 & 9.
  • Troubling: ranked between 10 & 14.
  • Of concern: ranked between 15 & 20.

While the bug rank describes severity, the confidence factor reflects the likelihood of these bugs to be flagged as real ones. The confidence was originally called priority, but it was renamed in the new version.


Of course, some defects can be open to interpretation, and they can even exist without causing any harm to the desired behavior of a software. That’s why, in a real-world situation, we need to properly configure static analysis tools by choosing a limited set of defects to activate in a specific project.


3.3. Eclipse Configuration


FindBugs plugin makes it easy to customize the bugs analysis strategy, by offering various ways to filter warning and limit the strictness of the results. You can check the configuration interface by going to Window -> Preferences -> Java -> FindBugs:

FindBugs插件通过提供各种方式来过滤警告和限制结果的严格性,从而使定制错误分析策略变得容易。你可以通过进入Window -> Preferences -> Java -> FindBugs来检查配置界面。

fb preferences 1


You can freely uncheck unwanted categories, raise the minimum rank to report, specify the minimum confidence to report, and customize markers for bugs ranks – Warning, Info, or Error.


FindBugs divide defects in many categories:


  • Correctness – gathers general bugs, e.g. infinite loops, inappropriate use of equals(), etc
  • Bad practice, e.g. exceptions handling, opened streams, Strings comparison, etc
  • Performance, e.g. idle objects
  • Multithreaded correctness – gathers synchronization inconsistencies and various problems in a multi-threaded environment
  • Internationalization – gathers problems related to encoding and application’s internationalization
  • Malicious code vulnerability – gathers vulnerabilities in code, e.g. code snippets that can be exploited by potential attackers
  • Security – gathers security holes related to specific protocols or SQL injections
  • Dodgy – gathers code smells, e.g. useless comparisons, null checks, unused variables, etc

Under the Detector configuration tab, you can check the rules you’re supposed to respect in your project:


fb preferences_detector 1

The speed attribute reflects how costly the analysis will be. The fastest the detector, the smallest the resources consumed to perform it.


You can find the exhaustive list of bugs recognized by FindBugs at the official documentation page.


Under the Filter files panel, you can create custom file filters, in order to include/exclude parts of the code-base. This feature is useful – for example – when you want to prevent “unmanaged” or “trash” code, defects to pop up in the reports, or may exclude all classes from the test package for instance.

过滤文件面板下,您可以创建自定义文件过滤器,以便包括/排除代码库的部分内容。这个功能很有用,例如,当你想防止 “未管理 “或 “垃圾 “代码、缺陷在报告中出现时,或者可以排除测试包中的所有类。

4. FindBugs IntelliJ IDEA Plugin

4.FindBugs IntelliJ IDEA插件

4.1. Installation


If you are an IntelliJ IDEA fan, and you want to start inspecting Java code using FindBugs, you can simply grab the plugin installation package from the official JetBrains site, and extract it to the folder %INSTALLATION_DIRECTORY%/plugins. Restart your IDE and you’re good to go.

如果您是 IntelliJ IDEA 的粉丝,并希望开始使用 FindBugs 检查 Java 代码,您可以简单地从JetBrains 官方网站上获取插件安装包,并将其解压到 %INSTALLATION_DIRECTORY%/plugins 文件夹中。重新启动你的IDE,你就可以了。

Alternatively, you can navigate to Settings -> Plugins and search all repositories for FindBugs plugin.

或者,你可以导航到 “设置”->”插件”,在所有软件库中搜索FindBugs插件。

By the time of writing this article, the version 1.0.1 of the IntelliJ IDEA plugin is just out,

在写这篇文章的时候,1.0.1版本的IntelliJ IDEA插件刚刚出来。

To make sure that the FindBugs plugin is properly installed, check for the option labeled “Analyze project code” under Analyze -> FindBugs.

要确保FindBugs插件已正确安装,请检查在Analyze -> FindBugs下标有 “分析项目代码 “的选项。

4.2. Reports Browsing


In order to launch static analysis in IDEA, click on “Analyze project code”, under Analyze -> FindBugs, then look for the FindBugs-IDEA panel to inspect the results:

为了在IDEA中启动静态分析,点击 “分析项目代码”,在Analyze -> FindBugs下,然后寻找FindBugs-IDEA面板来检查结果。

Spring rest analysis 1

You can use the second column of commands on the left side of the screenshot, to group defects using different factors:


  1. Group by a bug category.
  2. Group by a class.
  3. Group by a package.
  4. Group by a bug rank.

It is also possible to export the reports in XML/HTML format, by clicking the “export” button in the fourth column of commands.

也可以通过点击第四列命令中的 “导出 “按钮,将报告以XML/HTML格式导出。

4.3. Configuration


The FindBugs plugin preferences pages inside IDEA is pretty self-explanatory:


IntelliJ Preferences 1

This settings window is quite similar to the one we’ve seen in Eclipse, thus you can perform all kinds of configuration in an analogous fashion, starting from analysis effort level, bugs ranking, confidence, classes filtering, etc.


The preferences panel can be accessed inside IDEA, by clicking the “Plugin preferences” icon under the FindBugs-IDEA panel.

通过点击FindBugs-IDEA面板下的 “插件偏好 “图标,可以在IDEA内部访问偏好面板。

5. Report Analysis for the Spring-Rest Project


In this section we’re going to shed some light on a static analysis done on the spring-rest project available on Github as an example:


Spring rest analysis 2

Most of the defects are minor — Of Concern, but let’s see what we can do to fix some of them.


Method ignores exceptional return value:


File fileServer = new File(fileName);

As you can probably guess, FindBugs is complaining about the fact that we’re throwing away the return value of the createNewFile() method. A possible fix would be to store the returned value in a newly declared variable, then, log something meaningful using the DEBUG log level — e.g. “The named file does not exist and was successfully created” if the returned value is true.


The method may fail to close stream on exception: this particular defect illustrates a typical use case for exception handling that suggests to always close streams in a finally block:


try {
    DateFormat dateFormat 
      = new SimpleDateFormat("");
    String fileName = dateFormat.format(new Date());
    File fileServer = new File(fileName);
    byte[] bytes = file.getBytes();
    BufferedOutputStream stream 
      = new BufferedOutputStream(new FileOutputStream(fileServer));
    return "You successfully uploaded " + username;
} catch (Exception e) {
    return "You failed to upload " + e.getMessage();

When an exception is thrown before the stream.close() instruction, the stream is never closed, that’s why it’s always preferable to make use of the finally{} block to close streams opened during a try/catch routine.


An Exception is caught when Exception is not thrown: As you may already know, catching Exception is a bad coding practice, FindBugs thinks that you must catch a most specific exception, so you can handle it properly. So basically manipulating streams in a Java class, catching IOException would be more appropriate than catching a more generic Exception.


Field not initialized in the constructor but dereferenced without null check: it always a good idea to initialize fields inside constructors, otherwise, we should live with the possibility that the code will raise an NPE. Thus, it is recommended to perform null checks whenever we’re not sure if the variable is properly initialized or not.


6. Conclusion


In this article, we’ve covered the basic key points to use and customize FindBugs in a Java project.


As you can see, FindBugs is a powerful, yet simple static analysis tool, it helps to detect potential quality holes in your system – if tuned and used correctly.


Finally, it is worth mentioning that FindBugs can also be run as part of a separate continuous automatic code review tool like Sputnik, which can be very helpful to give the reports a lot more visibility.


The sample code we used for static analysis is available over on Github.