Maven 不僅能管理依賴、構建生命週期,配合 Maven Assembly Plugin 還能輕鬆生產開箱即用的發布包(zip、tar.gz 等)。本文通過一個 Web 專案實例,演示從零開始構建包含源碼、編譯產物、配置文件的完整發布包流程。
PATH 環境變量mvn archetype:create \
-DgroupId=de.focusdv.bcs \
-DartifactId=myweb \
-DarchetypeArtifactId=maven-archetype-webapp
生成標準目錄結構:
myweb/
├── deploy/ # 組裝插件配置目錄(手動創建)
├── output/ # 發布包輸出目錄(手動創建)
├── dist/ # 打包產物存放目錄(手動創建,如 war 包)
├── src/
│ ├── main/
│ │ ├── java/
│ │ ├── resources/
│ │ └── webapp/
│ └── test/
├── target/ # Maven 構建輸出
└── pom.xml
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>myweb</artifactId>
<name>myweb</name>
<version>1.0-SNAPSHOT</version>
<build>
<directory>output</directory>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>distribution.xml</descriptor>
</descriptors>
</configuration>
</plugin>
</plugins>
</build>
</project>
關鍵點:appendAssemblyId=false 避免產生 myweb-1.0-SNAPSHOT-distribution.zip 這類帶分類器的文件名,直接輸出 myweb-1.0-SNAPSHOT.zip。
<assembly>
<id>distribution</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>true</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>../dist</directory>
<outputDirectory>/</outputDirectory>
</fileSet>
<fileSet>
<directory>../src</directory>
<includes>
<include>**/*.xml</include>
</includes>
<outputDirectory>/</outputDirectory>
</fileSet>
</fileSets>
</assembly>
說明:將 dist/ 下所有文件(如 war 包)與 src/ 下所有 XML 配置文件打包到壓縮包根目錄。
切換到 deploy/ 目錄執行:
mvn assembly:assembly
成功後可在 output/ 目錄找到 myweb-1.0-SNAPSHOT.zip,內容結構清晰,可直接交付客戶或部署環境。
output/ 建議配置為獨立於源碼倉庫的外部目錄fileSets 包含腳本、文檔、授權文件等maven-release-plugin 實現版本發布自動化