<dependencyManagement>用于集中声明依赖版本和scope供子模块按需继承,避免父POM中<dependencies>导致的依赖污染;子模块引用时可省略version和scope,未声明则不引入,配合BOM更规范。

在 Maven 多模块项目中,<dependencyManagement> 的作用不是直接引入依赖,而是**集中声明依赖的版本和范围(scope)等元信息**,供子模块按需引用——子模块仍需显式声明 <dependency>,但可省略 <version> 和 <scope>,从而实现版本统一管控。
为什么不能只靠父 POM 的 dependencies?
父 POM 中的 <dependencies> 会**强制继承并生效**到所有子模块,容易造成不必要的依赖污染(比如测试依赖泄露到生产模块)。而 <dependencyManagement> 是“声明不导入”,只有子模块主动写 <dependency> 时才真正引入,且自动继承已声明的版本。
在父 POM 中定义 dependencyManagement
在根项目的 pom.xml(packaging=“pom”)中添加:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.18</version>
</dependency>
</dependencies>
</dependencyManagement>子模块中引用时省略 version 和 scope
子模块的 pom.xml 中只需写:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<!-- 不写 version,也不写 scope,自动继承父中定义 -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- version 自动为 2.7.18 -->
</dependency>
</dependencies>- 若子模块需要不同版本,可显式覆盖
<version>(不推荐,破坏统一性) - 若父中定义了
<scope>(如 test),子模块不写 scope 就默认采用该值 - 子模块未声明的依赖,即使父中出现在
dependencyManagement里,也不会被引入
配合 BOM(Bill of Materials)更规范
对于 Spring Boot、Spring Cloud 等生态,推荐直接 import 官方 BOM:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.7.18</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>这样能一次性导入整套兼容版本,比逐个声明更可靠,也支持多层 import(如先 import Spring Boot,再 import Spring Cloud,后者可覆盖前者部分版本)。


















