如何让Maven检查documentation.md版本与pom.xml版本一致,否则终止构建?
Maven配置:检查文档版本与工件版本一致性
可以通过maven-antrun-plugin结合Ant任务实现该需求,以下是具体配置方案:
核心配置(添加到pom.xml的<build><plugins>中)
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>3.1.0</version> <executions> <execution> <id>check-documentation-version</id> <phase>verify</phase> <goals> <goal>run</goal> </goals> <configuration> <target> <!-- 仅在非快照版本时触发检查 --> <condition property="perform.version.check"> <not> <contains string="${project.version}" substring="-SNAPSHOT"/> </not> </condition> <if> <isset property="perform.version.check"/> <then> <!-- 读取documentation.md文件内容 --> <loadfile property="doc.content" srcfile="documentation.md"/> <!-- 检查是否存在匹配的版本字符串,不匹配则终止构建 --> <containsregexp string="${doc.content}" pattern="Version: ${project.version}" casesensitive="true"> <fail message="ERROR: documentation.md中的版本与pom.xml工件版本不一致!当前pom版本为${project.version}"/> </containsregexp> </then> </if> </target> </configuration> <dependencies> <!-- 引入ant-contrib以支持条件判断语法 --> <dependency> <groupId>ant-contrib</groupId> <artifactId>ant-contrib</artifactId> <version>1.0b3</version> <exclusions> <exclusion> <groupId>ant</groupId> <artifactId>ant</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </execution> </executions> </plugin>
配置说明
- 触发时机:绑定到
verify阶段,确保代码编译、测试等核心构建步骤完成后再执行版本检查 - 非快照版本限制:通过Ant的
condition和if标签判断,仅当pom.xml中的版本不包含-SNAPSHOT后缀时,才执行检查逻辑 - 检查逻辑:
- 读取
documentation.md的全部内容到内存 - 用正则匹配检查内容中是否存在
Version: ${project.version}格式的字符串(${project.version}会自动替换为pom中的工件版本) - 若未匹配到,则抛出错误信息并终止整个Maven构建流程
- 读取
- 无自动更新:配置仅包含检查逻辑,不会修改
documentation.md中的任何内容
内容的提问来源于stack exchange,提问作者Lii
相关产品推荐
相关产品推荐

