如何不修改pom.xml覆盖依赖版本?含properties中lombok版本覆盖需求
如何在不修改pom.xml的情况下覆盖依赖版本及Properties配置
针对你提出的两个问题,我整理了几个实际工作中常用的方案,完全不用改动项目里的pom.xml文件:
1. 覆盖任意依赖的版本
不管pom里是用变量还是硬编码的版本号,都可以通过以下方式覆盖:
命令行临时指定(快速测试用)
如果只是临时测试某个版本,直接在Maven命令后加-D参数就行:- 要是依赖版本是用properties变量引用的(比如
${guava.version}),直接覆盖变量值:mvn clean install -Dguava.version=31.1-jre - 要是依赖版本是硬编码的,用
groupId:artifactId:version的格式指定新版本:mvn clean install -Dcom.google.guava:guava:31.1-jre
- 要是依赖版本是用properties变量引用的(比如
settings.xml配置(长期生效用)
如果你需要每次构建都用指定版本,不想每次敲命令行参数,可以在本地的~/.m2/settings.xml里加一个激活的profile:<settings> <profiles> <profile> <id>override-dependency-versions</id> <dependencyManagement> <dependencies> <!-- 在这里声明你要覆盖的依赖版本 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> </dependency> </dependencies> </dependencyManagement> </profile> </profiles> <!-- 激活这个profile --> <activeProfiles> <activeProfile>override-dependency-versions</activeProfile> </activeProfiles> </settings>这样每次执行Maven命令时,都会自动用这里指定的版本覆盖pom里的配置。
2. 覆盖Properties节点中声明的依赖版本
当然可以!而且操作更简单,因为Properties里的版本变量就是用来统一管理依赖版本的,直接覆盖变量值就行:
命令行快速覆盖
比如你要把lombok.version从1.18.16改成1.18.30,直接执行:mvn clean install -Dlombok.version=1.18.30所有引用
${lombok.version}的地方(包括依赖、插件配置等)都会自动用上新版本。settings.xml长期生效
同样在settings.xml的profile里添加Properties配置即可:<settings> <profiles> <profile> <id>override-properties</id> <properties> <lombok.version>1.18.30</lombok.version> <!-- 可以同时覆盖多个变量 --> <spring.boot.version>2.7.12</spring.boot.version> </properties> </profile> </profiles> <activeProfiles> <activeProfile>override-properties</activeProfile> </activeProfiles> </settings>
注意事项
要留意Maven的版本优先级:dependencyManagement里的版本 > Properties变量 > 依赖自身声明的版本。如果你的pom里dependencyManagement是硬编码的版本,那直接覆盖Properties变量是没用的,这时候需要用上面第一种方法里的dependencyManagement覆盖方式。
内容的提问来源于stack exchange,提问作者Mehraj Malik
相关产品推荐
相关产品推荐

