如何在Maven 3.9.6中用最新deploy插件仅部署Jar不部署Pom
问题背景
将Spring Boot项目的Maven版本从3.6.3升级到3.9.6后,执行deploy:deploy-file命令时出现行为变化:
- 旧版本仅部署指定的Jar包到Nexus,不会上传pom.xml
- 新版本(搭配maven-deploy-plugin 3.0.0+)即使指定了
-DgeneratePom=false,仍会同时部署Jar包和pom.xml
通过mvn -X调试发现,插件是从Jar包内部的META-INF/maven目录读取pom.xml并上传的。
原因分析
maven-deploy-plugin在3.0.0版本后调整了generatePom=false参数的行为:
- 2.8.2及更早版本:该参数会完全跳过pom.xml的部署流程
- 3.0.0及以上版本:当
generatePom=false时,插件会优先尝试从指定路径读取pom.xml;若未指定,则自动扫描Jar包内的META-INF/maven目录,找到pom.xml后就会上传
Spring Boot默认打包的Jar会包含META-INF/maven目录(存储项目的pom元数据),这就是新版本插件会自动上传pom.xml的核心原因。
解决方案(保留Maven 3.9.6+最新插件)
方案1:部署时显式指定无效的pomFile路径
在deploy命令中添加-DpomFile=/dev/null(Linux/macOS)或-DpomFile=NUL(Windows),让插件找不到pom.xml文件,从而跳过上传:
mvn deploy:deploy-file -DgroupId=com.example -DartifactId=example-artifact -Dversion=1.2.3 -DgeneratePom=false -Dpackaging=jar -DrepositoryId=nexus -Durl=https://my-nexus-address.com/nexus/repository/my-maven-releases -Dfile=example-artifact/target/example-artifact-1.2.3-jar-with-dependencies.jar -DpomFile=/dev/null
原理:插件3.0.0+版本中,当generatePom=false时,会优先使用指定的pomFile;若该路径无效(文件不存在),则不会自动从Jar包内读取pom.xml,最终仅部署Jar包。
方案2:构建Jar时排除META-INF/maven目录
修改项目pom.xml的打包配置,让Spring Boot打包时不生成META-INF/maven目录,这样插件就找不到可上传的pom.xml:
<build> <plugins> <!-- 配置maven-jar-plugin排除目录 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.3.0</version> <configuration> <excludes> <exclude>META-INF/maven/**</exclude> </excludes> </configuration> </plugin> <!-- 若使用spring-boot-maven-plugin,补充以下配置 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>3.2.0</version> <configuration> <excludes> <exclude> <groupId>*</groupId> <artifactId>*</artifactId> <type>pom</type> </exclude> </excludes> </configuration> </plugin> </plugins> </build>
注意:移除Jar内的Maven元数据可能影响部分依赖工具的解析逻辑,需根据项目实际场景评估风险。
方案3:使用插件新增的skipPom参数
maven-deploy-plugin 3.0.0+新增了skipPom参数,可直接控制是否跳过pom.xml的部署,比generatePom=false更直接:
方式1:命令行添加参数
mvn deploy:deploy-file -DgroupId=com.example -DartifactId=example-artifact -Dversion=1.2.3 -DgeneratePom=false -Dpackaging=jar -DrepositoryId=nexus -Durl=https://my-nexus-address.com/nexus/repository/my-maven-releases -Dfile=example-artifact/target/example-artifact-1.2.3-jar-with-dependencies.jar -Ddeploy.skipPom=true
方式2:项目pom.xml全局配置
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-deploy-plugin</artifactId> <version>3.1.1</version> <configuration> <skipPom>true</skipPom> </configuration> </plugin> </plugins> </build>
原理:skipPom=true会强制插件跳过pom.xml的上传流程,无论是否能找到pom文件。
内容的提问来源于stack exchange,提问作者Codinio

