如何让Maven dependencyManagement继承spring-boot-parent版本并添加排除项?
我希望在自定义父pom的dependencyManagement块中配置依赖时,既能继承spring-boot-parent的dependencyManagement中的版本,又能为该依赖添加排除项,这样子模块就无需重复配置排除项。
我的父pom继承自spring-boot-parent:
<artifactId>my-parent</artifactId> <version>1.0.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> <relativePath/> </parent> <dependencyManagement> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>???</version> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> </dependencyManagement>
子pom继承my-parent:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> </dependencies>
我尝试了几种方法,但都存在问题:
- 用
${parent.version}替换???时,子模块中版本解析为my-parent的1.0.0-SNAPSHOT,不符合预期; - 使用
${parent.parent.version}会导致Maven报错,因为它不支持该属性; - 直接写死版本
2.0.1.RELEASE可正常工作,但更新Spring Boot版本时需同步修改,不够便捷; - 无法在my-parent中提取
2.0.1.RELEASE作为属性来指定父版本,Maven不支持该操作; - 尝试使用spring-boot-parent继承的属性,但未找到对应版本属性。
请问有没有合适的方法实现我的需求?
其实Spring Boot的父pom早就为我们考虑到这种场景了——它在底层依赖的spring-boot-dependencies里定义了所有官方starter的版本属性,你直接用对应的属性就能搞定,既不用写死版本,又能保留排除项配置。
针对你的spring-boot-starter,对应的版本属性是${spring-boot.version},这个属性在spring-boot-starter-parent里已经帮你定义好了,直接拿来用就行:
<artifactId>my-parent</artifactId> <version>1.0.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> <relativePath/> </parent> <dependencyManagement> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>${spring-boot.version}</version> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> </dependencyManagement>
这么做的好处一目了然:
- 版本完全继承Spring Boot父pom的版本,以后要升级Spring Boot,只需要改父pom里
spring-boot-starter-parent的版本号就行,不用手动同步spring-boot-starter的版本; - 子模块引入
spring-boot-starter时,会自动带上这个排除项,再也不用每个子模块都重复写一遍; - 完全符合Maven的依赖管理逻辑,不会出现版本解析混乱的问题。
如果你好奇Spring Boot都定义了哪些版本属性,可以去看spring-boot-dependencies的pom文件,里面的properties块列了所有官方依赖的版本属性,比如log4j2.version对应log4j的版本,spring-cloud.version对应Spring Cloud的版本等等。
另外提一句,如果你不需要spring-boot-starter-parent提供的插件默认配置(比如maven-compiler-plugin的版本),也可以选择直接继承spring-boot-dependencies,但大多数情况下,继承spring-boot-starter-parent会更省心,因为它已经帮我们把基础插件配置都搞定了。
最后验证一下:当你把父pom里的spring-boot-starter-parent版本改成2.7.15,${spring-boot.version}会自动变成2.7.15,子模块里的spring-boot-starter版本也会同步更新,排除项依然生效,完美满足你的需求。
内容的提问来源于stack exchange,提问作者zbstof

