Maven打包
學習的樂字節的版本
1. 前言
對於Maven項目,我們可以通過pom.xml配置的方式來實現打包時的環境選擇,通過maven只需要簡單的配置,就可以完成在不同環境下項目的整體打包。
2. 建立完整的目錄結構
- 這里使用IDEA創建一個Maven項目,完整目錄結構大致如下:

- Java:Java源碼文件夾
- resources:配置資源文件夾,包含xml文件、properties文件等
- webapp:資源目錄,存放jsp、html以及靜態資源如css、js等
-
添加不同環境下對應的配置文件(本地環境、測試環境、正式環境)
3. 在pom.xml文件中添加profile配置
與dependencies標簽同級,配置打包環境
如果有多個運行環境的話,才進行這樣的配置,方便按照實際需求,給不同環境打包
<!-- 打包環境配置:開發環境、測試環境、正式環境 -->
<profiles>
<!-- 開發環境 -->
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<!--未指定環境時,默認打包環境設置為dev下的環境-->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!-- 測試環境 -->
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<!-- 正式環境 -->
<profile>
<id>product</id>
<properties>
<env>product</env>
</properties>
</profile>
</profiles>
4. 設置資源文件配置
在build標簽中,設置項目資源的配置:
<resources>
<resource>
<directory>src/main/resources/${env}</directory>
</resource>
<resource>
<directory>src/main/java/</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
<include>**/*.tld</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
5. 執行打包操作
IDEA右上角打開Run/Debug Configuarations窗口
輸入對應的打包命令(command line):package(簡單打包命令)
關於command line:
-
clean compile package -Dmaven.test.skip=true
打包默認環境(開發環境)並且跳過maven測試操作
-
clean compile package -Ptest -Dmaven.test.skip=true
打包測試環境並且跳過maven測試操作
-
clean compile package -Pproduct -Dmaven.test.skip=true
打包生成環境並且跳過maven測試操作
這里使用package命令進行打包
打包成功:會顯示打包成功后存放的目錄
不同的項目打包的結果一般不一樣,比如,普通Java項目一般會打包成jar包,web項目打成war包(就可以部署在服務器中)