文章目录
- [Maven中引入 springboot 相关依赖的方式](#Maven中引入 springboot 相关依赖的方式)
-
- [1. 不使用版本管理(不推荐)](#1. 不使用版本管理(不推荐))
- 2、使用版本管理(推荐)
-
- [2.1 继承 spring-boot-starter-parent](#2.1 继承 spring-boot-starter-parent)
- [2.2 使用 spring-boot-dependencies + 自定义父工程](#2.2 使用 spring-boot-dependencies + 自定义父工程)
- [2.3引入 spring-framework-bom](#2.3引入 spring-framework-bom)
Maven中引入 springboot 相关依赖的方式
1. 不使用版本管理(不推荐)
如果项目中没有统一版本管理,那么每个依赖都必须显式声明 <version>
。
示例:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>2.7.4</version>
</dependency>
⚡ 缺点: 手动指定,容易出错,不推荐。
2、使用版本管理(推荐)
2.1 继承 spring-boot-starter-parent
在 pom.xml 中直接继承:
xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.4</version>
</parent>
然后添加依赖时,无需再写<version>
:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.2 使用 spring-boot-dependencies + 自定义父工程
如果因为公司项目有自定义父 POM,又想用 Spring Boot 的统一版本管理,可以在 <dependencyManagement>
中导入:
xml
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.7.4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
然后添加依赖时,同样无需再写<version>
。
2.3引入 spring-framework-bom
有时候,项目需要单独控制 Spring Framework 的各模块版本,比如在某些 JDK8 项目中,想让 Spring Framework 尽可能用最新兼容版本,这时候可以引入 spring-framework-bom,专门管理 Spring Framework 的依赖版本。
示例:
xml
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>${spring.framework.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
然后就可以像下面这样引入 Spring Framework 的具体模块而不用单独写版本:
xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
⚡ 注意:
- spring-framework-bom 只管理 Spring Framework 本身(如 spring-core、spring-web、spring-context),不包括 Spring Boot 的 starter 或其他自动配置模块。
- spring-boot-dependencies不仅管自己家的东西(上述 Spring Framework 本身),还顺便帮你管好了外部合作伙伴,比如:Jackson、Tomcat、MySQL 驱动、Redis 客户端等。