1. 简介
在构建 Spring Boot 应用时,我们经常会用到一个非常重要的 Maven 依赖:spring-boot-starter-parent
。它不仅为我们提供了统一的依赖管理,还默认配置了常用的 Maven 插件,帮助我们快速启动项目。
本文将介绍:
spring-boot-starter-parent
是什么- 如何利用它管理依赖版本和插件配置
- 如何自定义或覆盖默认配置
- 以及在不使用它的场景下,如何仍然使用其依赖管理机制
2. Spring Boot Starter Parent 是什么?
spring-boot-starter-parent
是一个特殊的 Starter 项目,它本身不是一个功能模块,而是为 Spring Boot 项目提供:
✅ 统一的依赖管理
✅ 默认的 Maven 插件配置
✅ 继承自 spring-boot-dependencies
的完整依赖树
它简化了我们引入依赖时的版本管理,避免了手动指定每个依赖的版本号。
要在项目中使用它,只需在 pom.xml
中添加如下内容:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.5</version>
</parent>
你可以在 Maven Central 找到最新版本。
3. 依赖管理
一旦你将 spring-boot-starter-parent
设置为项目 parent,就可以在 <dependencies>
中直接引用其管理的依赖,而无需指定版本号。
比如,添加一个 Web 模块的 Starter:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Maven 会自动使用 spring-boot-starter-parent
中定义的版本来下载依赖。
4. 使用 dependencyManagement 覆盖依赖版本
如果你需要使用某个依赖的特定版本,而不是 starter-parent
提供的默认版本,可以使用 <dependencyManagement>
来显式指定。
例如,覆盖 Spring Data JPA 的版本:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>3.1.5</version>
</dependency>
</dependencies>
</dependencyManagement>
这样,即使其他地方引用了该依赖,也会使用你在这里定义的版本。
5. 利用 Properties 自定义配置
spring-boot-starter-parent
中通过 <properties>
标签定义了许多默认配置,包括 Java 版本、插件版本、依赖版本等。
我们可以直接在自己的 pom.xml
中重新定义这些属性来覆盖默认值。
比如,修改 JUnit 的版本:
<properties>
<junit.version>4.11</junit.version>
</properties>
6. 覆盖其他属性配置
除了依赖版本,还可以通过属性来修改插件版本、Java 版本、编码方式等。
比如,修改 Java 编译版本:
<properties>
<java.version>17</java.version>
</properties>
这将影响所有插件中与 Java 版本相关的配置,比如 maven-compiler-plugin
的编译目标版本。
7. 不使用 Starter Parent 的情况
有些项目可能已经有一个自定义的 Maven Parent,或者你不想使用默认的配置。
这时,你仍然可以通过 <dependencyManagement>
引入 spring-boot-dependencies
,从而获得其依赖管理能力。
例如,使用自定义的 parent:
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-boot-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
然后手动引入 Spring Boot 的依赖树:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>3.1.5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
✅ 这样做可以保留依赖管理的优势,同时又不依赖 spring-boot-starter-parent
。
⚠️ 但需要注意,某些默认插件配置可能不会自动应用,需要手动补充。
8. 总结
spring-boot-starter-parent
是 Spring Boot 项目中推荐使用的父级项目,它通过统一的依赖管理和默认插件配置,简化了项目构建流程。
主要优势包括:
- 自动管理依赖版本
- 提供常用插件的标准配置
- 支持通过 properties 和 dependencyManagement 覆盖默认配置
- 即使不使用 parent,也可以通过 import 机制引入依赖管理
掌握这些内容,有助于你更高效地构建和维护 Spring Boot 项目。