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 還得自己調
- 網上的解決方案大部分都不靠譜,寫的也很莫名其妙
- 自己總結的經驗才是最可靠的