Maven打包可执行jar,同时指定依赖的jar

时间:2022-04-23 19:11:04

在pom的plugins中配置

[html] view plain copy
  1. <plugin>    
  2.      <groupId>org.apache.maven.plugins</groupId>    
  3.      <artifactId>maven-compiler-plugin</artifactId>    
  4.      <configuration>    
  5.          <defaultLibBundleDir>lib</defaultLibBundleDir>    
  6.          <source>1.6</source>    
  7.          <target>1.6</target>    
  8.          <encoding>UTF-8</encoding>    
  9.      </configuration>    
  10.  </plugin>    
  11.  <!-- 打包jar文件时,配置manifest文件,加入lib包的jar依赖 -->    
  12.  <plugin>    
  13.      <groupId>org.apache.maven.plugins</groupId>    
  14.      <artifactId>maven-jar-plugin</artifactId>    
  15.      <configuration>    
  16.          <archive>    
  17.              <manifest>    
  18.                  <addClasspath>true</addClasspath>    
  19.                  <classpathPrefix>lib/</classpathPrefix>    
  20.                  <mainClass>主类的完全路径名</mainClass>    
  21.              </manifest>    
  22.          </archive>    
  23.      </configuration>    
  24.  </plugin>    
  25.  <!-- 拷贝依赖的jar包到lib目录 -->    
  26.  <plugin>    
  27.      <groupId>org.apache.maven.plugins</groupId>    
  28.      <artifactId>maven-dependency-plugin</artifactId>    
  29.      <executions>    
  30.          <execution>    
  31.              <id>copy</id>    
  32.              <phase>package</phase>    
  33.              <goals>    
  34.                  <goal>copy-dependencies</goal>    
  35.              </goals>    
  36.              <configuration>    
  37.                  <outputDirectory>    
  38.                      ${project.build.directory}/lib    
  39.                  </outputDirectory>    
  40.              </configuration>    
  41.          </execution>    
  42.      </executions>    
  43.  </plugin>    
  44.  <!-- 解决资源文件的编码问题 -->    
  45.  <plugin>    
  46.      <groupId>org.apache.maven.plugins</groupId>    
  47.      <artifactId>maven-resources-plugin</artifactId>    
  48.      <version>2.3</version>    
  49.      <configuration>    
  50.          <encoding>UTF-8</encoding>    
  51.      </configuration>    
  52.  </plugin>   

执行mvn package以后,会在target下生成可执行jar以及lib,lib里包含依赖的jar.

可执行的jar如果解开看的话会发现里面Main-Class以及Class-Path都已经设置好了,后者指向当前路径的lib路径下