文章來源
https://blog.csdn.net/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 見證奇蹟~~