乐于分享
好东西不私藏

10 个提高代码质量的 Maven 插件,pom.xml 里加一行就生效

10 个提高代码质量的 Maven 插件,pom.xml 里加一行就生效

一、引言

代码质量是团队协作的基石,但手动检查效率低下且容易遗漏。Maven 插件提供了自动化的解决方案,只需在 pom.xml 中配置即可在构建过程中自动执行检查。

今天我要分享 10 个实用的 Maven 插件,涵盖代码格式化、漏洞扫描、测试覆盖率等多个维度。


二、零配置就能用的插件

2.1 sortpom-maven-plugin:POM 自动排序

作用:自动按照标准顺序排序 pom.xml 中的元素,保持团队风格一致。

配置

<plugin><groupId>com.github.ekryd.sortpom</groupId><artifactId>sortpom-maven-plugin</artifactId><version>3.2.0</version><executions><execution><phase>verify</phase><goals><goal>sort</goal></goals><configuration><sortFile>/.sortpom/sortorder.xml</sortFile><createBackupFile>false</createBackupFile></configuration></execution></executions></plugin>

使用

# 检查并排序mvn sortpom:sort# 只检查不修改mvn sortpom:check

2.2 versions-maven-plugin:一键检查依赖更新

作用:检查项目中所有依赖是否有新版本可用。

配置

<plugin><groupId>org.codehaus.mojo</groupId><artifactId>versions-maven-plugin</artifactId><version>2.16.0</version></plugin>

使用

# 检查所有依赖的新版本mvn versions:display-dependency-updates# 检查插件版本更新mvn versions:display-plugin-updates# 检查父 POM 版本更新mvn versions:display-parent-updates# 自动升级所有依赖(谨慎使用)mvn versions:use-latest-releases

三、需要简单配置的插件

3.1 spotless-maven-plugin:代码格式化一把梭

作用:统一代码风格,支持 Java、Kotlin、XML、YAML 等多种文件格式。

⚠️ 注意:默认只验证不修改,需要配置 spotless:apply 才能自动格式化。

配置

<plugin><groupId>com.diffplug.spotless</groupId><artifactId>spotless-maven-plugin</artifactId><version>2.49.0</version><configuration><java><googleJavaFormat><version>1.23.0</version><style>AOSP</style></googleJavaFormat><removeUnusedImports/></java><xml><indent>4</indent><sortAttributes>true</sortAttributes></xml></configuration><executions><execution><phase>verify</phase><goals><goal>check</goal></goals></execution></executions></plugin>

使用

# 检查代码格式(CI 中使用)mvn spotless:check# 自动格式化代码(开发中使用)mvn spotless:apply

自定义格式化规则

<java><formatAnnotations/><trimTrailingWhitespace/><endWithNewline/><custom><sortImports><staticImportsFirst>true</staticImportsFirst><groupByPackage>true</groupByPackage></sortImports></custom></java>

3.2 modernizer-maven-plugin:检测旧版 API

作用:检测代码中使用了已废弃或旧版 JDK API 的地方,Java 版本迁移利器。

配置

<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>modernizer-maven-plugin</artifactId><version>2.8.0</version><configuration><javaVersion>21</javaVersion><failOnViolation>true</failOnViolation><violationsFile>modernizer-violations.xml</violationsFile></configuration><executions><execution><phase>verify</phase><goals><goal>modernizer</goal></goals></execution></executions></plugin>

使用

# 检测旧版 API 使用mvn modernizer:modernizer

常见违规示例

// 会被检测到的旧版 APIjava.util.Date date = new java.util.Date();  // 推荐 java.time.LocalDateTimeThread.currentThread().stop();               // 已废弃sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();  // 内部 API

四、安全扫描类插件

4.1 dependency-check-maven:OWASP 漏洞扫描

作用:扫描项目依赖中的已知安全漏洞(CVE),CI 中可配置中断高危依赖。

配置

<plugin><groupId>org.owasp</groupId><artifactId>dependency-check-maven</artifactId><version>9.2.0</version><configuration><failBuildOnCVSS>7.0</failBuildOnCVSS><format>ALL</format><outputDirectory>${project.build.directory}/dependency-check-report</outputDirectory></configuration><executions><execution><phase>verify</phase><goals><goal>check</goal></goals></execution></executions></plugin>

使用

# 执行漏洞扫描mvn dependency-check:check# 生成 HTML 报告mvn dependency-check:aggregate

报告解读

漏洞等级
CVSS 评分
处理方式
Critical
≥ 9.0
立即修复
High
7.0 - 8.9
优先级修复
Medium
4.0 - 6.9
计划修复
Low
0.1 - 3.9
评估后决定

⚠️ 注意:首次运行会下载 NVD 数据库,可能需要几分钟时间。

4.2 spotbugs-maven-plugin:静态代码分析

作用:检测代码中的潜在 Bug、安全漏洞和性能问题。

⚠️ 注意:FindBugs 已废弃,SpotBugs 是其继任者。

配置

<plugin><groupId>com.github.spotbugs</groupId><artifactId>spotbugs-maven-plugin</artifactId><version>4.8.6.0</version><configuration><effort>max</effort><threshold>medium</threshold><failOnError>true</failOnError><excludeFilterFile>spotbugs-exclude.xml</excludeFilterFile></configuration><executions><execution><phase>verify</phase><goals><goal>check</goal></goals></execution></executions><dependencies><dependency><groupId>com.github.spotbugs</groupId><artifactId>spotbugs</artifactId><version>4.8.6</version></dependency></dependencies></plugin>

使用

# 执行代码分析mvn spotbugs:check# 生成报告mvn spotbugs:spotbugs# 打开报告mvn spotbugs:gui

常见检测项

  • 空指针引用
  • 资源未关闭
  • 并发问题
  • SQL 注入风险
  • 硬编码密码

五、代码规范类插件

5.1 maven-checkstyle-plugin:代码风格检查

作用:检查代码是否符合指定的编码规范(如 Google Style、Sun Style)。

配置

<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-checkstyle-plugin</artifactId><version>3.4.0</version><configuration><configLocation>checkstyle.xml</configLocation><failOnViolation>true</failOnViolation><violationSeverity>warning</violationSeverity><includeTestSourceDirectory>true</includeTestSourceDirectory></configuration><executions><execution><phase>verify</phase><goals><goal>check</goal></goals></execution></executions></plugin>

使用

# 检查代码风格mvn checkstyle:check# 生成报告mvn checkstyle:checkstyle

自定义检查规则(checkstyle.xml):

<?xml version="1.0"?><!DOCTYPE modulePUBLIC"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN""https://checkstyle.org/dtds/configuration_1_3.dtd"><modulename="Checker"><propertyname="charset"value="UTF-8"/><modulename="TreeWalker"><modulename="ConstantName"/><modulename="LocalVariableName"/><modulename="MemberName"/><modulename="MethodName"/><modulename="PackageName"/><modulename="TypeName"/><modulename="EmptyBlock"/><modulename="LineLength"><propertyname="max"value="120"/></module><modulename="MethodLength"><propertyname="max"value="50"/></module><modulename="ParameterNumber"><propertyname="max"value="5"/></module></module></module>

5.2 maven-pmd-plugin:代码质量分析

作用:检测代码中的潜在问题,如循环复杂度过高、重复代码等。

配置

<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-pmd-plugin</artifactId><version>3.24.0</version><configuration><rulesets><ruleset>rulesets/java/quickstart.xml</ruleset><ruleset>rulesets/java/basic.xml</ruleset><ruleset>rulesets/java/design.xml</ruleset></rulesets><failOnViolation>true</failOnViolation><failurePriority>5</failurePriority><includeTests>true</includeTests></configuration><executions><execution><phase>verify</phase><goals><goal>check</goal></goals></execution></executions></plugin>

使用

# 执行代码分析mvn pmd:check# 生成报告mvn pmd:pmd# 检查重复代码mvn pmd:cpd-check

常见检测项

  • 循环复杂度过高(建议 < 15)
  • 方法行数过多
  • 参数数量过多
  • 重复代码块
  • 未使用的变量

六、测试覆盖率类插件

6.1 jacoco-maven-plugin:测试覆盖率报告

作用:生成代码测试覆盖率报告,支持指令覆盖、分支覆盖、方法覆盖等多种维度。

配置

<plugin><groupId>org.jacoco</groupId><artifactId>jacoco-maven-plugin</artifactId><version>0.8.11</version><configuration><rules><rule><element>PACKAGE</element><limits><limit><counter>LINE</counter><value>COVEREDRATIO</value><minimum>0.8</minimum></limit><limit><counter>BRANCH</counter><value>COVEREDRATIO</value><minimum>0.7</minimum></limit></limits></rule></rules></configuration><executions><execution><goals><goal>prepare-agent</goal></goals></execution><execution><id>report</id><phase>test</phase><goals><goal>report</goal></goals></execution><execution><id>check</id><phase>verify</phase><goals><goal>check</goal></goals></execution></executions></plugin>

使用

# 运行测试并生成报告mvn test# 查看报告open target/site/jacoco/index.html# 检查覆盖率是否达标mvn jacoco:check

覆盖率指标

指标
含义
建议阈值
Line Coverage
行覆盖率
≥ 80%
Branch Coverage
分支覆盖率
≥ 70%
Method Coverage
方法覆盖率
≥ 85%
Class Coverage
类覆盖率
≥ 90%

七、构建约束类插件

7.1 maven-enforcer-plugin:构建约束

作用:强制构建环境符合指定条件,如 JDK 版本、Maven 版本、依赖版本等。

配置

<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-enforcer-plugin</artifactId><version>3.4.0</version><executions><execution><id>enforce-maven</id><goals><goal>enforce</goal></goals><configuration><rules><requireMavenVersion><version>3.6.0</version></requireMavenVersion><requireJavaVersion><version>21</version><message>项目要求使用 Java 21</message></requireJavaVersion><dependencyConvergence/><banDuplicatePomDependencyVersions/></rules><fail>true</fail></configuration></execution></executions></plugin>

常用规则

规则
作用
requireMavenVersion
强制 Maven 版本
requireJavaVersion
强制 JDK 版本
dependencyConvergence
检测依赖版本冲突
banDuplicatePomDependencyVersions
禁止重复声明依赖版本
requirePluginVersions
强制声明插件版本

八、完整 pom.xml 示例

<build><plugins><!-- 代码格式化 --><plugin><groupId>com.diffplug.spotless</groupId><artifactId>spotless-maven-plugin</artifactId><version>2.49.0</version><configuration><java><googleJavaFormat/><removeUnusedImports/></java></configuration></plugin><!-- 旧版 API 检测 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>modernizer-maven-plugin</artifactId><version>2.8.0</version><configuration><javaVersion>21</javaVersion><failOnViolation>true</failOnViolation></configuration></plugin><!-- 漏洞扫描 --><plugin><groupId>org.owasp</groupId><artifactId>dependency-check-maven</artifactId><version>9.2.0</version><configuration><failBuildOnCVSS>7.0</failBuildOnCVSS></configuration></plugin><!-- 静态代码分析 --><plugin><groupId>com.github.spotbugs</groupId><artifactId>spotbugs-maven-plugin</artifactId><version>4.8.6.0</version></plugin><!-- 代码风格检查 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-checkstyle-plugin</artifactId><version>3.4.0</version><configuration><configLocation>checkstyle.xml</configLocation></configuration></plugin><!-- 代码质量分析 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-pmd-plugin</artifactId><version>3.24.0</version></plugin><!-- 测试覆盖率 --><plugin><groupId>org.jacoco</groupId><artifactId>jacoco-maven-plugin</artifactId><version>0.8.11</version></plugin><!-- 构建约束 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-enforcer-plugin</artifactId><version>3.4.0</version></plugin><!-- POM 排序 --><plugin><groupId>com.github.ekryd.sortpom</groupId><artifactId>sortpom-maven-plugin</artifactId><version>3.2.0</version></plugin><!-- 依赖版本检查 --><plugin><groupId>org.codehaus.mojo</groupId><artifactId>versions-maven-plugin</artifactId><version>2.16.0</version></plugin></plugins></build>

九、插件对比总结

插件
作用
配置复杂度
CI 集成
spotless
代码格式化
modernizer
旧版 API 检测
versions
依赖版本检查
dependency-check
OWASP 漏洞扫描
spotbugs
静态代码分析
checkstyle
代码风格检查
pmd
代码质量分析
jacoco
测试覆盖率
enforcer
构建约束
sortpom
POM 排序

十、最佳实践

10.1 分阶段引入

第一阶段:基础保障(必选)    ├── enforcer(构建约束)    ├── sortpom(POM 排序)    └── spotless(代码格式化)第二阶段:安全扫描(必选)    ├── dependency-check(漏洞扫描)    └── spotbugs(静态分析)第三阶段:质量提升(推荐)    ├── checkstyle(代码风格)    ├── pmd(质量分析)    ├── jacoco(测试覆盖率)    └── modernizer(API 检测)第四阶段:维护工具(按需)    └── versions(依赖更新)

10.2 CI 集成策略

# .gitlab-ci.yml 示例stages:-build-test-verifybuild:stage:buildscript:-mvncompilespotless:checktest:stage:testscript:-mvntestjacoco:reportverify:stage:verifyscript:-mvnverify-mvndependency-check:check-mvnspotbugs:check

10.3 渐进式严格化

// 初期:只警告不中断构建<failOnViolation>false</failOnViolation>// 中期:团队适应后开启中断<failOnViolation>true</failOnViolation><violationSeverity>error</violationSeverity>// 后期:提高标准<minimum>0.9</minimum>  // jacoco 覆盖率要求

十一、总结

这 10 个 Maven 插件覆盖了代码质量的各个方面:

  • 代码格式化:spotless
  • 安全扫描:dependency-check、spotbugs
  • 代码规范:checkstyle、pmd
  • 测试质量:jacoco
  • 环境约束:enforcer、modernizer
  • 项目维护:versions、sortpom

核心原则

  • 零配置插件优先引入,快速见效
  • 需要配置的插件逐步完善,避免一开始就过度严格
  • CI 集成是关键,自动化检查才能持续保障质量
  • 团队共识比工具更重要,先统一规范再用工具强制执行

💡 互动话题:你在项目中使用哪些代码质量工具?效果如何?欢迎在评论区分享你的经验!