springboot結合maven打包釋出
本篇分享如何使用maven便利我們打springboot的釋出包;我這裡使用的是idea開發工具,首先建立了多個module的專案結構,如圖:
要對多個module的專案做打包,一般情況都是在父級pom中配置打包的外掛,其他module的pom不需要特別的配置,當配置完成後,點選idea中maven工具的package,就能執行一系列打包操作;
這裡先使用maven-jar-plugin外掛,在父級pom中新增配置如下:
1 <!--通過maven-jar-plugin外掛打jar包--> 2 <plugin> 3<groupId>org.apache.maven.plugins</groupId> 4<artifactId>maven-jar-plugin</artifactId> 5<version>2.4</version> 6<configuration> 7<archive> 8<manifest> 9<addClasspath>true</addClasspath> 10<classpathPrefix>lib/</classpathPrefix> 11<!--main入口--> 12<mainClass>com.platform.WebApplication</mainClass> 13</manifest> 14</archive> 15<!--包含的配置檔案--> 16<includes> 17</includes> 18<excludes> 19</excludes> 20</configuration> 21 </plugin>
上面的配置我們需要注意以下幾個節點:
- mainClass:我們需要指定main入口,當然這不是必須的,如果同一個project中有多個main入口,那打包的時候才需要,僅僅就一個main入口這個其實忽略;
- classpathPrefix:指定加入classpath中依賴包所在的字首資料夾名
- addClasspath:依賴包放加入到classpath中,預設true
- includes:需要包含在jar中的檔案,一般不配置(注意:如果配置路徑不合適,可能會吧class排除掉)
- excludes:如果是要做jar包外部配置檔案的話,這裡需要用excludes排除這些配置檔案一起打包在jar中
使用maven-jar-plugin外掛針對專案工程來打包,這個時候通過maven的package命令打包,能看到jar中有一個lib資料夾(預設),其中包含了工程專案中所引入的第三方依賴包,通過java -jar xxx.jar能看到jar成功啟動:
在規範的專案中,一般有dev,test,uat,pro等環境,針對這些個環境需要有不同的配置,springboot中可以通過application-dev|test|...yml來區分不同的配置,僅僅需要在預設的application.yml中加入spring.profiles.active=dev|test...就行了;
這種方式有個不便的地方,比如本地除錯或釋出上線都需要來回修改active的值(當然通過jar啟動時,設定命令列active引數也可以),不是很方便;下面採用在pom中配置profiles,然後通過在idea介面上滑鼠點選選擇啟動所用的配置;首先,在main層建立配置檔案目錄如下結構:
為了區分測試,這裡對不同環境配置檔案設定了server.port來指定不同埠(dev:3082,pro:3182)
然後,在父級pom中配置如下profiles資訊:
1<profiles> 2<profile> 3<id>dev</id> 4<!--預設執行配置--> 5<activation> 6<activeByDefault>true</activeByDefault> 7</activation> 8<properties> 9<activeProfile>dev</activeProfile> 10</properties> 11</profile> 12<profile> 13<id>test</id> 14<properties> 15<activeProfile>test</activeProfile> 16</properties> 17</profile> 18<profile> 19<id>uat</id> 20<properties> 21<activeProfile>uat</activeProfile> 22</properties> 23</profile> 24<profile> 25<id>pro</id> 26<properties> 27<activeProfile>pro</activeProfile> 28</properties> 29</profile> 30</profiles>
節點說明:
- activeByDefault:設定為預設執行配置
- activeProfile:所選擇的啟動配置,它的值對應上面建立profiles下面的dev|test|pro資料夾
然後,在pom中的build增加resources節點配置:
1 <resources> 2<!--指定所使用的配置檔案目錄--> 3<resource> 4<directory>src/main/profiles/${activeProfile}</directory> 5</resource> 6 </resources>
此刻我們的配置就完成了,正常情況下idea上maven模組能看到這樣的圖面:
這個時候僅僅只需要我們勾選這些個按鈕就行了,不管是除錯還是最後打包,都按照這個來獲取所需的配置檔案。