0. 序
前段时间,闲着没事将个人电脑上的 IDEA 换成了最新版本,Maven 也更新为最新版本,但是发现 IDEA 和 Maven 的集成时,关于依赖 jar 包的更新出现了问题,这里简单记录一下出现的问题以及解决的方案~
1. 准备
Cris 使用的 IDEA 版本如下(当下最新版本)

Maven 版本升级成最新的 3.6.0
为了方便问题的展示,这里 Cris 新建一个平时开发最常用的项目架构 首先新建一个父模块 father



然后选中 father 模块,我们可以以 father 模块作为父模块,新建我们的子模块,每个子模块负责不同的业务




2. 问题概述
实际开发中,我们都是用父模块做依赖包的管理,如下
<groupId>com.cris</groupId>
<artifactId>father</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>son1</module>
<module>son2</module>
</modules>
<properties>
<fastjson.version>1.2.51</fastjson.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
父模块引入了一个 fastjson 的第三方 jar 包,我们使用 dependencyManagement 标签为管理 jar 包,关于 dependencyManagement 和 dependencies 标签的不同,这里不再赘述,大家可以理解为父模块 dependency 标签管理的 jar 包,都会被子模块引入;
但是如果是 dependencyManagement 标签管理的 jar 包则在子模块显示引入的时候才会被导入到子模块中,不理解的同学可以 参考
子模块 son1 的 pom.xml 如下
<parent>
<artifactId>father</artifactId>
<groupId>com.cris</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>son1</artifactId>

当我们显示的在子模块引入 fastjson 包的时候,
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
</dependencies>
(因为版本由 father 模块控制,子模块就可以不用引入 fastjson 的版本号),我们发现子模块无法引入父模块定义的 jar 包

3. 解决方案
很简单,打开 IDEA 的 Maven 设置



在 son2 子模块的 pom.xml 中同样引入 fastjson 的依赖
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
</dependencies>
可以发现,现在 son1 和 son2 子模块引入来自 father 的 jar 包都成功了

version 标签

如果想为所有的子模块更换 fastjson 的版本号,只需要在 father 模块中更改即可
<properties>
<fastjson.version>1.2.47</fastjson.version>
</properties>
我们再看看 son1 模块的依赖

例如:修改 son2 模块的依赖
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
</dependencies>
即便 father 模块 fastjson 的版本是 1.2.47,son2 模块因为显示的指定优先级更高

4. 总结
- 工具不要总是想用最新的,否则出了诡异的 bug 还得自己调
- 网上的解决方案大部分都不靠谱,写的也很莫名其妙
- 自己总结的经验才是最可靠的