为什么 Spring Boot 项目加上就可以更新版本?

最近 log4j2 的核弹级漏洞席卷了大部分互联网公司,升级版本成了这两周的核心任务。对于要升级到什么版本,最新版本 2.16.0 是最佳选择。那么如何快速升级,之前也给出了 Spring Boot 项目升级版本的最简方法 。
大家只需要使用这样的简单配置,就可以把 log4j2 一系列包的版本都升级了。

如果这种方法不行,注意加了配置之后要 reload 下。另外,如果你不是 Spring Boot 项目,或者是通过其他方式引入的 log4j2,那么需要单独处理,或者在你项目的根依赖里,直接写上 log4j2 的依赖并设置版本为 2.16.0,强制覆盖其他地方引入的版本。
上面的配置很简单,但还是有读者不清楚为什么这样就可以了:

所以,今天就具体给大家说一下这个配置的原理。
一步步了解为什么
下面我会以读代码寻找源头的方式,带你一步步了解这个配置。希望你通过本文除了知道这个问题是为什么,还能学会这种自己探究问题的方法。
第一步:观察下你的 pom.xml ,有没有发现很多依赖包括非 Spring Boot Starter 的依赖都没有写 version?

既然没 version 也能跑,那一定有地方定义了!把焦点转移到 parent 上,似乎就这里有 version!
第二步:进一步查看 spring-boot-starter-parent 的内容

进入后可以看到类似下面的 xml 配置,其中主要包含的内容是与 build 相关的,而非依赖信息。

第三步:继续观察 spring-boot-starter-parent 中的信息中,可以看到,它还有一个 parent,好小子藏那么深!那么就继续深入查看 spring-boot-dependencies 的内容:

进入后,我们就可以看到重点了,该 Spring Boot 版本下各个组件的版本参数就在这里:

搜索 log4j2 ,可以发现,这个版本下默认使用的是 2.14.1 :

继续往下搜,在 dependencyManagement 节点下,可以看到各个依赖的版本定义就是引用了上面配置的各个 properties :

所以,当我们在自己的 Spring Boot 中配置对应的 properties ,就可以覆盖 parent 中的 properties ,并实现版本的更新。
此文章来源于分享,
原文链接:https://www.toutiao.com/article/7042528227511943692/?log_from=18d76ded5b9a5_1659506238832
评论