Maven - Exemple de SpotBugs
Dans cet article, nous allons vous montrer comment utiliserSpotBugs Maven Plugin pour trouver des bogues dans le code Java.
Note
Findbugs is no longer maintained, et donc SpotBugs est le successeur spirituel de FindBugs
P.S SpotBugs requires JDK 1.8
1. Plugin Maven SpotBugs
Définissez lesspotbugs-maven-plugin
dans la balisereporting
. Pour quemvn site
génère le rapport SpotBugs.
pom.xml
com.github.spotbugs spotbugs-maven-plugin 3.1.8
2. Code Java
Un code Java simple, avec un champ inutilisé «abc» et un problème de performances dans la boucle «+ string». Plus tard, SpotBugs pourra le détecter et l'afficher sur le rapport.
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. Site Maven
mvn compile site
pour générer un site Maven pour le projet Java, le rapport SpotBugs sera généré et intégré au site Maven automatiquement.
$ 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] ------------------------------------------------------------------------
Télécharger le code source
$ git clone https://github.com/example/maven-examples.git
$ cd maven-static-code-analysis
$ mvn compile site