Spring Boot项目默认的会打包成单一的jar文件,但是有时候我们并不想让配置文件、依赖包都跟可执行文件打包到一起。这时候可以在pom.xml文件中进行配置,从而使资源文件、依赖包和可执行文件分离。pom.xml配置如下:
<build>
<plugins>
<!--**********分离资源文件及依赖包打包配置*************-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>target/lib</outputDirectory>
<excludeTransitive>false</excludeTransitive>
<stripVersion>false</stripVersion>
<includeScope>runtime</includeScope>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
<exclude>static/**</exclude>
<exclude>templates/**</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<layout>ZIP</layout>
<includes>
<include>
<groupId>non-exists</groupId>
<artifactId>non-exists</artifactId>
</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>classes</classifier>
<attach>false</attach>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<property name="dist">target/build</property>
<property name="res">target/build/resources</property>
<property name="dist-tmp">target/build/tmp</property>
<property name="app-name">${project.artifactId}-${project.version}</property>
<property name="real-app-name">${project.artifactId}</property>
<delete dir="${dist}" />
<mkdir dir="${dist}" />
<mkdir dir="${dist-tmp}" />
<mkdir dir="${res}" />
<copy file="target/${app-name}.jar" tofile="${dist-tmp}/${app-name}.jar" />
<unzip src="${dist-tmp}/${app-name}.jar" dest="${dist-tmp}" />
<delete file="${dist-tmp}/${app-name}.jar" />
<move file="target/${app-name}-classes.jar" tofile="${dist}/${real-app-name}.jar"/>
<move todir="${dist}/lib">
<fileset dir="target/lib" />
</move>
<delete dir="${dist-tmp}" />
<copy todir="${res}">
<fileset dir="target/classes">
<include name="**/static/**" />
<include name="**/templates/**" />
</fileset>
</copy>
<copy todir="${res}">
<fileset dir="target/classes">
<include name="**/*.properties" />
<include name="**/*.xml" />
<include name="**/*.yml" />
</fileset>
</copy>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
maven打包完成后,可以在target目录下看到一个build目录,进入该目录的结构如图:
test.jar文件就是可执行文件,资源文件和配置文件都在resources目录下,依赖的jar包都在lib目录下。
运行方式:java -jar -Dloader.path=.,resources,lib test.jar
注意:如果在windows10系统下运行,要用cmd,不要用PowerShell,否则可能会报Error: Unable to access jarfile .path=.,resources,lib异常。