Maven 打 jar 包
项目 jar 包和依赖 jar 包分离
项目单独打成一个 jar 包,项目依赖的 jar 包统一拷贝指定目录
在项目的 pom.xml 中添加如下配置:
<project>
<!-- ... -->
<build>
<!-- ... -->
<plugins>
<!-- ... -->
<!-- Maven Jar Plugin -->
<!-- 用于构建 jar 包 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>
<!-- 如果 addClasspath 为 true>
<!-- 则下面填写 classpath 的目录前缀>
lib/
</classpathPrefix>
<mainClass>
<!-- 这里填写主类名 -->
com.example.App
</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<!-- Maven Dependency Plugin -->
<!-- 用于将依赖复制到指定位置 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>
<!-- 这里填写依赖输出目录 -->
<!-- 必须和上面填写的 classpathPrefix 相对应 -->
${project.build.directory}/lib
</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
运行如下命令进行打包:
mvn package
输出结构(有省略):
target
├── lib
│ ├── dependency-1.jar
│ ├── dependency-2.jar
│ └── dependency-3.jar
└── demo-1.0.jar
其中 demo-1.0.jar 是我们项目的 jar,lib 目录下的 jar 是依赖的 jar。
使用方法:
java -jar demo-1.0.jar
使用时,lib 目录和构建成果 demo-1.0.jar 必须处于同一目录下。
项目和依赖打成同一个 jar 包
在项目的 pom.xml 中添加如下配置:
<project>
<!-- ... -->
<build>
<!-- ... -->
<plugins>
<!-- ... -->
<!-- Maven Assembly Plugin -->
<!-- 将项目输出合并到一个包含依赖项、模块、站点文档和其他文件的单个可分发存档中 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archive>
<manifest>
<mainClass>
<!-- 这里填写主类名 -->
com.example.App
</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
运行如下命令进行打包:
mvn package
输出结构(有省略):
target
├── demo-1.0-jar-with-dependencies.jar
└── demo-1.0.jar
其中 demo-1.0.jar 是不带依赖的 jar 包,demo-1.0-jar-with-dependencies.jar 是带依赖的 jar 包。
使用方法:
java -jar demo-1.0-jar-with-dependencies.jar
参考:Maven - 打包可执行 jar 包 | 简书