文章来源
https://blog.youkuaiyun.com/chasonsp/article/details/88852353
折腾的几天,使用maven打包后发现了问题,首先是打包的配置文件读取问题,使用getResource().getPah()会发现在访问jar包的文件时,路径里会有感叹号(杠杠滴~~)是这样的 …jar!..
经过不断的查找资料及反复验证后,终于找到了可行的方法:
首先填个引用来的图片:
也就是通过这个图得到的启发。
一、关于打包jar后配置文件访问问题:
1.不常用的配置文件(如log4j的配置文件等),放在src/main/resource路径保存。
2.常用的配置文件在根目录下自己建立conf文件夹保存。
访问方式为建立相应的常量:
public static final String XXXX_CONF = System.getProperty("user.dir") + File.separator + "conf" + File.separator + "XXXX.properties";
二、打包jar,在pom中添加如下配置:
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<!-- 可执行jar插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<outputDirectory>${project.build.directory}/java</outputDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.xxx.xxx.xxx</mainClass>
</manifest>
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<!-- 依赖包插件 -->
<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>${project.build.directory}/java/lib</outputDirectory>
<!-- 是否不包含间接依赖 -->
<excludeTransitive>false</excludeTransitive>
<!-- 忽略版本 -->
<stripVersion>false</stripVersion>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
或者
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<!-- 可执行jar插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.xxx.xxx.xxx</mainClass>
</manifest>
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<!-- 依赖包插件 -->
<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>
<!-- 是否不包含间接依赖 -->
<excludeTransitive>false</excludeTransitive>
<!-- 忽略版本 -->
<stripVersion>false</stripVersion>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
三,打包,执行maven clean 和 maven install后
1.会生成相应的jar文件和lib文件夹(里面是依赖的jar包)
2.将conf及下面文件copy到jar所在的路径下
3.执行 java -jar xxx.jar 见证奇迹~~