1. 程式人生 > >Maven打包可執行jar 分離配置檔案和lib

Maven打包可執行jar 分離配置檔案和lib


類:

classloader 產生的resourceAsStream只能載入classpath下的配置檔案,如果想載入其他目錄的檔案需要使用file的形式,maven專案src/main/resources/對應classpath,這個路徑下的檔案不打包,所以不能使用resourceAsStream這種方式載入,需要換成fileinputstream.

package com.too.m2.hello_m2;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class TestMainClass {

	public static void main(String[] args) throws IOException {
		//此種載入方式只能載入classpath下的檔案,不打包classpath下的檔案時候需要用其他方式生成inputStream,在打好的jar所在目錄下建立src/main/resources目錄,1.txt放在該目錄下即可載入到
//		InputStream in = TestMainClass.class.getClassLoader().getResourceAsStream("1.txt"); 
		FileInputStream in = new FileInputStream("src/main/resources/1.txt");
		Properties properties = new Properties();
		properties.load(in);
		String property = properties.getProperty("username");
		System.out.println(property);
		
		JSONObject parse = (JSONObject) JSON.parse("{'name':'lisi'}");
		System.out.println(parse.toJSONString());
	}

}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.too.m2</groupId>
	<artifactId>hello-m2</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>hello-m2</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.24</version>
		</dependency>
	</dependencies>
	<build>
		<!-- 不打包*.txt -->
		<resources>
				<resource>
					<directory>src/main/resources</directory>
					<excludes>
						<exclude>*.txt</exclude>
					</excludes>
				</resource>
		</resources>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-jar-plugin</artifactId>
					<version>2.4</version>
					<configuration>
						<archive>
							不打包依賴的jar,把依賴的jar copy到lib目錄,和生成的jar放在同一級目錄下
							<manifest> 
								<addClasspath>true</addClasspath>
								<classpathPrefix>lib/</classpathPrefix>
								<mainClass>com.too.m2.hello_m2.TestMainClass</mainClass>
							</manifest>
						</archive>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

最後生成的jar 和lib包 以及src\main\resources\1.txtx三者在同一目錄下,lib裡需要手動新增依賴的jar

現在就可以執行test.jar了