依赖管理

我们创建一个SpringBoot项目,导入了Web依赖(省略步骤)。我们可以看到每个SpringBoot项目中的pom.xml都会有一个父项目parent

image-20201224170207429

1
2
3
4
5
6
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

这个父项目就是做依赖管理的。例如我们可以发现我导入的web,test依赖是没有写版本号的。

image-20201224170423690

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

但是却导入2.4.1了的版本依赖。这是为什么呢??

image-20201224170528784

我们点开当前父项目spring-boot-starter-parent

image-20201224170633663

发现它也存在一个父项目spring-boot-dependencies点开查看。

image-20201224170749612

我们发现这里声明了许多属性,并且还使用了dependencyManagement对依赖进行了管理。

image-20201224170900509

我们搜索spring-boot-starter-web可以看到这里对其依赖进行了管理,版本为我们先前看到的2.4.1

image-20201224171000680

搜索logback也能看到与我们的导入的版本号是一致的。

image-20201224171309446

spring-boot-starter-parent的父项目spring-boot-dependencies几乎声明了所有开发中常用的依赖的版本号,被称为自动版本仲裁机制。

但是如果我们不想使用这个版本的依赖怎么修改呢??例如我们导入mysql-connector-java

image-20201224171855208

导入的是spring-boot-dependencies中声明的mysql版本。

image-20201224171942391

如果要修改成使用5.1.32的mysql驱动。则可以version标签指定版本为5.1.32

1
2
3
4
5
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>

image-20201224172128060

或者在当前项目中的pom.xml。在properties标签中声明mysql.versioin(与spring-boot-dependencies中的保持一致)值为5.1.32

image-20201224172617167

这两种方式都可以。

总结

  1. 每个SpringBoot项目都有一个父项目spring-boot-starter-parent。它又有一个父项目spring-boot-dependencies这里声明管理了绝大部分的依赖版本。被称为自动版本仲裁机制。
  2. 因此引入版本仲裁依赖默认都可以不写版,本引入非版本仲裁的jar,要写版本号。
  3. 修改默认版本号可以直接在下面声明version版本,或者 查看spring-boot-dependenciesproperties里面规定当前依赖的版本用的 key。在当前项目里面重写配置properties的key值。