首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Maven Assembly Plugin 實戰:打造 Java 專案發布包

     編輯:Java 相關知識

前言

Maven 不僅能管理依賴、構建生命週期,配合 Maven Assembly Plugin 還能輕鬆生產開箱即用的發布包(zip、tar.gz 等)。本文通過一個 Web 專案實例,演示從零開始構建包含源碼、編譯產物、配置文件的完整發布包流程。

環境準備

  1. 安裝 Maven 2.x 並配置 PATH 環境變量
  2. 使用 Archetype 快速生成 Web 專案骨架:
    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

編寫組裝配置

1. deploy/pom.xml —— 組裝專案 POM

<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。

2. deploy/distribution.xml —— 組裝描述符

<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 實現版本發布自動化
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved