Maven打包可执行jar 分离配置文件和lib

时间:2022-12-29 23:39:47

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

Maven打包可执行jar 分离配置文件和lib


现在就可以运行test.jar了