在日常开发中,开发进行代码检查的手段往往有四种
- 开发工具配置代码检查工具,例如
alibaba
的代码规范扫描,findBugs
- jenkins等上传代码时进行代码检查,例如可以配置
sonar
等 - 项目组人员之间的
code review
- maven插件进行扫描
这次就是介绍如何使用maven插件pmd
进行代码检查
maven插件pmd
的使用配置(本文使用的是alibaba的p3c)
1.在pom文件进行pmd插件的配置
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.8</version>
<configuration>
<!-- 规范的配置 -->
<rulesets>
<ruleset>src/main/resources/p3c-pmd/rulesets/java/ali-comment.xml</ruleset>
<ruleset>src/main/resources/p3c-pmd/rulesets/java/ali-concurrent.xml</ruleset>
<ruleset>src/main/resources/p3c-pmd/rulesets/java/ali-constant.xml</ruleset>
<ruleset>src/main/resources/p3c-pmd/rulesets/java/ali-exception.xml</ruleset>
<ruleset>src/main/resources/p3c-pmd/rulesets/java/ali-flowcontrol.xml</ruleset>
<ruleset>src/main/resources/p3c-pmd/rulesets/java/ali-naming.xml</ruleset>
<ruleset>src/main/resources/p3c-pmd/rulesets/java/ali-oop.xml</ruleset>
<ruleset>src/main/resources/p3c-pmd/rulesets/java/ali-orm.xml</ruleset>
<ruleset>src/main/resources/p3c-pmd/rulesets/java/ali-other.xml</ruleset>
<ruleset>src/main/resources/p3c-pmd/rulesets/java/ali-set.xml</ruleset>
</rulesets>
<printFailingErrors>true</printFailingErrors>
</configuration>
<executions>
<!-- 绑定pmd:check到verify生命周期 -->
<execution>
<id>pmd-check-verify</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
<!-- 绑定pmd:pmd到site生命周期 -->
<execution>
<id>pmd-pmd-site</id>
<phase>site</phase>
<goals>
<goal>pmd</goal>
</goals>
</execution>
</executions>
<!-- p3c依赖 -->
<dependencies>
<dependency>
<groupId>com.alibaba.p3c</groupId>
<artifactId>p3c-pmd</artifactId>
<version>1.3.6</version>
</dependency>
</dependencies>
</plugin>
2.配置生成站点报告的对应配置
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
<version>2.5</version>
</plugin>
</plugins>
</reporting>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
3.执行相关命令,生成报告
- 可以执行对应生命周期命令,如:mvn site,
- 也可以执行pmd的相关命令, 如: mvn pmd:pmd