使用場景:
在工作中使用maven管理項目時,需要将部分依賴包與開發的項目一起整合到一個jar檔案中運作,其餘的jar包放入axis2的lib檔案夾下提供支援。maven-dependency-plugin和maven-jar-plugin不能滿足需求,則需要用到maven assembly plugin這個強大的插件來分别生成。
使用說明:
在maven項目的pom檔案的build節點添加如下依賴:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<!-- 指定輸出的名稱 -->
<finalName>smsServerMvn_V6.0.1_20171018</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<!-- 配置包内jar的xml檔案路徑 -->
<descriptor>src/main/assembly/assembly.xml</descriptor>
<!-- 配置包外jar的xml檔案路徑 -->
<descriptor>src/main/assembly/generatorLib.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-jar</id>
<phase>package</phase>
<goals>
<goal>single</goal><!-- 執行一次 -->
</goals>
</execution>
</executions>
</plugin>
建立src/main/assembly檔案夾,此時項目結構如圖:

在assembly.xml檔案中添加如下配置:
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd">
<id>assembly-description</id>
<formats>
<format>jar</format>
</formats>
<!--壓縮包下是否生成和項目名相同的根目錄 -->
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>${project.basedir}\target\classes\com</directory>
<outputDirectory>com</outputDirectory>
</fileSet>
<fileSet>
<directory>src/main/resources/META-INF</directory>
<outputDirectory>META-INF</outputDirectory>
</fileSet>
</fileSets>
<dependencySets>
<dependencySet>
<!-- 解壓jar包 -->
<unpack>true</unpack>
<!-- jar包存放的路徑 -->
<outputDirectory>/</outputDirectory>
<!-- 需要的jar包 -->
<includes>
<include>com.oracle:ojdbc6</include>
<include>org.apache.mina:mina-core</include>
<include>com.dareway.basic:basic-core</include>
</includes>
</dependencySet>
</dependencySets>
</assembly>
- format:壓縮格式,有zip、tar、tar-gz、jar、war等。
- includeBaseDirectory:是否生成和項目名相同的根目錄,預設是true,打成的jar包中會生成一個以項目名稱為根的檔案夾。
- fileSets:設定配置檔案是否打進最終的jar包。常用的選項有檔案原路徑directory和輸出路徑outputDirectory
- dependencySets:設定依賴的jar包。unpack設定jar包是以.jar方式存進去還是以classes檔案的形式存進去(與fatjar工具類似),預設為false。outputDirectory設定依賴jar包存放的路徑。includes和excludes分别代表要将哪些jar包引入、将哪些jar包去除。如果沒有寫這兩個選項,預設是将pom檔案中所有的依賴生成到最終的jar檔案中。可選項:scope等。
第二個assembly配置檔案:(目的是将生成的jar放入外部的lib中)
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd">
<id>assembly-lib</id>
<formats>
<format>zip</format>
</formats>
<dependencySets>
<dependencySet>
<!-- jar包存放的路徑 -->
<outputDirectory>lib</outputDirectory>
<!-- 不需要的jar包 -->
<excludes>
<exclude>com.oracle:ojdbc6</exclude>
<exclude>org.apache.mina:mina-core</exclude>
<exclude>com.dareway.basic:basic-core</exclude>
</excludes>
</dependencySet>
</dependencySets>
</assembly>
執行mvn指令:clean package
最終在target目錄下生成了所需的jar包。
官方文檔有更詳細的說明:連結描述
http://maven.apache.org/compo...