在maven项目build时,有时候我们需要额外创建一个jar。这个需求可以用assembly功能实现。
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<manifest>
<mainClass>com.x.y.z.Xyz</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptors>
<descriptor>assembly-fat.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
pom中加入上面一段即可。其中mainClass部分是为了创建一个可运行jar。
jar中的文件内容需要在文件assembly-fat.xml中制定。这个文件和pom文件在一个目录下即可。其内容可以为:
<?xml version="1.0" encoding="UTF-8"?>
<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>fat</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>/</outputDirectory>
<useProjectArtifact>false</useProjectArtifact>
<unpack>true</unpack>
<scope>runtime</scope>
<excludes>
<exclude>org.slf4j:*</exclude>
<exclude>log4j:*</exclude>
</excludes>
</dependencySet>
</dependencySets>
<fileSets>
<fileSet>
<outputDirectory>/</outputDirectory>
<directory>${project.build.outputDirectory}</directory>
</fileSet>
</fileSets>
</assembly>
生成的文件名为pom生成的jar包中加入了上面的id, 例如xyz-1.0-SNAPSHOT-fat.jar。
描述符文件说明:
1、ID
id 标识符,添加到生成文件名称的后缀符。如果指定 id 的话,目标文件则是 ${artifactId}-${id}.tar.gz
2、formats
maven-assembly-plugin 支持的打包格式有zip、tar、tar.gz (or tgz)、tar.bz2 (or tbz2)、jar、dir、war,可以同时指定多个打包格式
<formats>
<format>dir</format>
...可配置多个
</formats>
3、dependencySets
用来定制工程依赖 jar 包的打包方式,核心元素如下:
元素 | 类型 | 作用 |
outputDirectory | String | 指定包依赖目录,该目录是相对于根目录 |
includes/include* | List<String> | 包含依赖 |
excludes/exclude* | List<String> | 排除依赖 |
<dependencySets>
<dependencySet>
<outputDirectory>lib</outputDirectory>
<scope>runtime</scope>
<excludes>
<exclude>${groupId}:${artifactId}</exclude>
</excludes>
</dependencySet>
</dependencySets>
4、fileSets
管理一组文件的存放位置,核心元素如下:
元素 | 类型 | 作用 |
outputDirectory | String | 指定包依赖目录,该目录是相对于根目录 |
includes/include* | List<String> | 包含依赖 |
excludes/exclude* | List<String> | 排除依赖 |
<fileSets>
<fileSet>
<directory>src/main/resources</directory>
<outputDirectory>/config</outputDirectory> <!--resource文件输出路径-->
</fileSet>
<fileSet>
<directory>src/main/bin</directory>
<outputDirectory>/</outputDirectory> <!--bin目录文件输出路径-->
</fileSet>
<fileSet>
<directory>${project.build.directory}</directory> <!--jar文件输出路径-->
<outputDirectory>/</outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
</fileSets>