公司新專案需使用java技術堆疊,便使用IDEA搭建了一個多SpringBoot專案的聚合工程,因為初次使用,遇到了很多問題,maven打包時各種報錯,在網上查了好多終于解決了,為鞏固記憶,特作此記錄,
一、先記錄一下創建父子工程一些需要注意的地方:
1.創建父子工程
在IDEA中使用Spring Initializr的方式創建SpringBoot工程,GroupId為域.公司名,例如com.company,Artifact為專案名,例如testproject,主要注意父子專案保持組名一致
父專案創建好后,將.mvm、src檔案夾,mvnw、mvnw.cmd檔案直接洗掉,并修改pom.xml的packaging更改為pom,
2.創建子工程
選中父專案,滑鼠右鍵,然后點擊New—>Module,同樣方式創建SpringBoot工程,注意專案的保存路徑要加上'\子專案名',否則專案工程會亂掉
3.修改子專案的pom.xml檔案,將其中的parent更改為對應父專案的資訊,如下:

4.父專案的pom.xml中增加modules節點,并增加新增的子專案

5.添加依賴參考
一般情況下是,在父專案的pom.xml中用dependencyManagement統一版本管理,子專案中根據需要自行宣告參考,
如下:
父專案pom.xml的properties中宣告jar包版本號

<dependencyManagement>
<dependencies>
<!-- SpringBoot的依賴配置-->
<dependency>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.3.4.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--阿里資料庫連接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!--Token生成與決議-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jwt.version}</version>
</dependency>
<!--驗證碼 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
....
<!-- 通用工具-->
<dependency>
<groupId>com.loxaump</groupId>
<artifactId>loxaump-common</artifactId>
<version>${loxaump.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
dependencyManagement依賴宣告
子專案中宣告所需參考,為防止子專案參考時,因為依賴jar包版本不一致,導致打包時找不到對應jar包錯誤(maven本地中會自動下載有依賴的版本),盡量子專案中不單獨宣告版本號,
<dependencies>
<!-- Spring框架基本的核心工具 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!-- SpringWeb模塊 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!-- spring security 安全認證 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
....
</dependencies>
子專案dependencies
二、maven打包時報錯 程式包不存在
父子專案創建好后,使用maven工具

其他的子專案依賴common專案,打包后,明明正常打好了common的jar包,在maven本地倉中也能找到對應的版本,但是在打其他專案時,仍會提示程式包 com.loxaump.common.service.contants不存在等一系列類找不到,
如下圖所示:

解決方法:
SpringBoot打成jar包我們一般使用spring-boot-maven-plugin這個插件,當配置了該插件后,運行“mvn package”進行打包時,會打包成一個可以直接運行的 JAR 檔案,使用“java -jar”命令就可以直接運行,
1.因為spring-boot-maven-plugin在打成jar包時會默認找public static void main(String[] args){***}方法,這時候如果專案有多個main方法,就有問題了,需要刪掉其他的main方法,只留SpringBoot的入口main方法,或者在pom.xml中用start-class屬性指定專案main方法:

2..將父專案ROOT中的spring-boot-maven-plugin更換成org.apache.maven.plugins

更改為:

encoding即為:UTF-8
修改后,在重新打包,問題解決,

補充
如果打包時,報錯:Cannot resolve xxx.xxx.xxx-xxx:unknown等錯誤時,應該是本地maven倉庫中存在多個版本的jar包,并且因為其他原因導致某個jar包下載失敗,這時,就到本地倉將jar包的檔案夾洗掉,重新使用maven打包下載即可,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/166182.html
標籤:其他
