Maven – SpotBugsの例
この記事では、SpotBugs Maven Pluginを使用してJavaコードのバグを見つける方法を紹介します。
Note
Findbugs is no longer maintained、したがってSpotBugsはFindBugsの精神的な後継者です
P.S SpotBugs requires JDK 1.8
1. Maven SpotBugsプラグイン
reporting
タグでspotbugs-maven-plugin
を定義します。 そのため、mvn site
はSpotBugsレポートを生成します。
pom.xml
com.github.spotbugs spotbugs-maven-plugin 3.1.8
2. Javaコード
使用されていないフィールド「abc」と「+文字列」ループのパフォーマンスの問題がある単純なJavaコード。 後で、SpotBugsはそれを検出し、レポートに表示できるようになります。
package com.example.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サイト
mvn compile site
を使用してJavaプロジェクトのMavenサイトを生成すると、SpotBugsレポートが生成され、Mavenサイトに自動的に統合されます。
$ 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] ------------------------------------------------------------------------
ソースコードをダウンロード
$ git clone https://github.com/example/maven-examples.git
$ cd maven-static-code-analysis
$ mvn compile site