1. 需求
maven默认package打包, 只包含项目代码, 没有引入项目代码依赖的lib包, 执行时缺包
那么如何将依赖的lib文件打进jar包呢?
2. Assembly插件
assembly插件用于maven工程打包, 将项目代码与依赖lib包打进一个jar文件中
单词: assembly, 组装, the process of putting together the parts of sth such as a vehicle or piece of furniture
The Assembly Plugin for Maven enables developers to combine project output into a single distributable archive that also contains dependencies, modules, site documentation, and other files.
2.1. 配置
<artifactId>maven-assembly-plugin</artifactId>
引入assembly插件<executions>
打包命令绑定到mvn package阶段<descriptorRef>
使用内置的jar-with-dependencies描述性文件 (内置的还有bin, src, project, 这里不作讨论), 工具提供的通用打jar包手段<manifest>
可执行jar包需要在MANIFEST.MF文件中指定Main-Class属性
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>xxx.yyy.zzz</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
2.2. jar-with-dependencies
描述如何打包, 将依赖的lib包拆包后再与项目代码打进jar包
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.1.0 http://maven.apache.org/xsd/assembly-2.1.0.xsd">
<!-- TODO: a jarjar format would be better -->
<id>jar-with-dependencies</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>/</outputDirectory>
<useProjectArtifact>true</useProjectArtifact>
<unpack>true</unpack>
<scope>runtime</scope>
</dependencySet>
</dependencySets>
</assembly>