Maven – SpotBugsの例

この記事では、Javaコードのバグを見つけるためにhttps://spotbugs.github.io/spotbugs-maven-plugin/[SpotBugs Maven Plugin]を使用する方法を説明します。
P.S SpotBugsにはJDK 1.8
が必要です
1. Maven SpotBugs Plugin
reporting`タグに
spotbugs-maven-plugin`を定義してください。そのため、 `mvn site`はSpotBugsレポートを生成します。
pom.xml
<reporting>
<plugins>
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>3.1.8</version>
</plugin>
</plugins>
</reporting>
2. Javaコード
未使用のフィールド ‘abc’と “string”ループでのパフォーマンスの問題を持つ単純なJavaコード。その後、SpotBugsはそれを検出してレポートに表示することができます。
package com.mkyong.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]------------------------------------------------------------------------
4. SpotBugsレポート
`target/site/spotbugs.html`のレポートを見直してください
リンク://wp-content/uploads/2018/11/maven-spotbugs-static-code.png[

]
5.よくある質問
5.1
SpotBugs 400のバグパターン
を確認します。
5.2その他のhttps://spotbugs.github.io/spotbugs-maven-plugin/usage.html[Maven SpotBugsプラグインのレシピはこちら]
ソースコードをダウンロードする
$ git clone
https://github.com/mkyong/maven-examples.git
$ cd maven-static-code-analysis $ mvnコンパイルサイト
#target/site/spotbugs.htmlのレポートを表示する
参考文献
Maven Plugin]。
https://spotbugs.readthedocs.io/ja/latest/maven.html
[
SpotBugs Maven Plugin]。
https://en.wikipedia.org/wiki/List
of
tools
for
static
code
analysis#Java[List
静的コード解析ツールの紹介]