父 pom.xml
<properties>
<spring.boot.version>2.2.13.RELEASE</spring.boot.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- 只需声明 groupId 和 artifactId,版本号会自动继承 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-legacy</artifactId>
<version>${spring.boot.version}</version>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</dependencyManagement>
子pom.xml
<dependencyManagement>
<dependencies>
<!-- 子模块只需声明 groupId 和 artifactId,版本号和排除项会自动继承 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-legacy</artifactId>
</dependency>
<!-- 其他依赖... -->
</dependencies>
</dependencyManagement>
在 Maven 中,<dependencyManagement>
元素位于项目的 pom.xml文件中,它扮演了一个集中管理依赖版本的角色。具体作用包括:
- 版本统一管理: 在
<dependencyManagement>
部分定义的依赖项,其 version、scope 和其它属性会被所有子模块所继承。这意味着,当各个子模块需要引用相同 groupId 和 artifactId 的依赖时,它们无需明确指定版本号。Maven 会自动查找并使用在父级 POM 中<dependencyManagement>
部分声明的对应版本。 - 依赖范围和排除管理: 不仅可以管理依赖版本,还可以在此处集中管理依赖的 scope(例如 compile、test 等)以及排除特定的传递依赖。这样,在子模块中引入依赖时,相关的 scope 和 exclusion 规则也会得到继承和应用。
- 简化项目结构: 通过
<dependencyManagement>
,项目可以避免在多个子模块之间重复配置相同的依赖信息,从而保持 POM 文件简洁,并减少版本冲突的风险。