如何在Maven中强制传递依赖最低版本且避免降级?
在Maven中实现Gradle依赖约束的三大特性
Gradle的依赖约束(dependency constraints)具备三个核心特性:
- 升级低版本传递依赖:若传递依赖的版本低于约束指定的最低版本,会自动将其升级至该版本
dependencies { implementation 'org.springframework.boot:spring-boot-starter-tomcat:2.7.18' constraints { implementation 'org.apache.tomcat.embed:tomcat-embed-core:9.0.84' // 将9.0.83升级至9.0.84 :) } }
- 不强制降级高版本:约束的版本会被父项目或BOM提供的更高版本覆盖,不会把已有的高版本降级
dependencies { implementation 'org.springframework.boot:spring-boot-starter-tomcat:2.7.18' constraints { implementation 'org.apache.tomcat.embed:tomcat-embed-core:9.0.82' // 不会把9.0.83降级到9.0.82 :) } }
- 无使用则不引入:如果对应的传递依赖未被直接依赖使用,约束不会将其纳入构建
dependencies { // implementation 'org.springframework.boot:spring-boot-starter-tomcat:2.7.18' constraints { implementation 'org.apache.tomcat.embed:tomcat-embed-core:9.0.84' // 无实际作用 :) } }
现在需要在Maven中实现这三个特性,但现有方案存在问题:
使用<dependencyManagement>的局限
<dependencyManagement>能满足升级低版本和无使用则不引入的特性,但会强制降级更高版本,需要频繁维护:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <version>2.7.18</version> <scope>provided</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <version>9.0.82</version> <!-- 会把9.0.83降级到9.0.82 :( --> </dependency> </dependencies> </dependencyManagement>
使用版本范围的问题
设置版本范围[x,)会总是使用范围内的最高版本,无法固定预期的最低版本:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <version>2.7.18</version> <scope>provided</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <version>[9.0.82,)</version> <!-- 总是使用最新版本 :( --> </dependency> </dependencies> </dependencyManagement>
期望效果
希望在Maven中实现类似Gradle的逻辑:设置的版本作为最低要求,若父项目或BOM有更高版本则优先使用该高版本,不强制降级:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <version>2.7.18</version> <scope>provided</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <version>9.0.82</version> <!-- 优先使用父项目提供的9.0.83版本 :) --> </dependency> </dependencies> </dependencyManagement>
内容的提问来源于stack exchange,提问作者Reed M
相关产品推荐
相关产品推荐

