jar读取目录配置、打包jar后无法获取目录下的配置

文章讲述了在Java中,将项目打包成jar后,如何正确读取src/main/resources下的配置文件,涉及到`PathMatchingResourcePatternResolver`原理和使用`JarURLConnection`处理jar文件中的资源.
摘要由CSDN通过智能技术生成

jar读取目录配置、打包jar后无法获取目录下的配置

jar读取目录配置、打包jar后无法获取目录下的配置。java打成jar包后获取不到配置文件路径。解决项目打成jar包上线无法读取配置文件。打包jar后无法读取resource下的配置文件

场景

需要读取 src/main/resources/mapper下的所有 xml 配置。

前提

代码打包成jar,查看这篇文章:https://lingkang.top/archives/idea-yuan-cheng-shi-diao-jar

原代码

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lingkang
 * @create by 2024/3/18 14:44
 */
public class Test05 {
    public static void main(String[] args) {
        String scanPath="mapper";
        List<String> result=new ArrayList<>();
        // 直接遍历,此时可能是idea、eclipse开发环境。
        URL resource = Test04.class.getClassLoader().getResource("");
        if (resource != null) {
            File file = new File(resource.getPath() + scanPath);
            if (file.listFiles() != null)
                for (File f : file.listFiles()) {
                    result.add(f.getPath());
                }
        }
        // 输出扫描结果
        System.out.println(result);
        // 加载配置
        /*for (String config:result){
            InputStream inputStream = Test04.class.getClassLoader().getResourceAsStream(config);
        }*/
    }
}

image-1710744353286

打包成jar后运行

java -jar mybatis-magic-test.jar

如何打包成jar请查看这篇文章:https://lingkang.top/archives/idea-yuan-cheng-shi-diao-jar

image-1710744419051

这时候获取到的是空值。

远程试调

如何试调jar,查看这篇文章:https://lingkang.top/archives/idea-yuan-cheng-shi-diao-jar

image-1710744615862

可以看到获取到是一个空对象

spring的底层原理

spring的底层实现是:PathMatchingResourcePatternResolver,它分多种情况,但总的来说,通配符时(例如/mapper/*.xml),是通过对jar所有文件进行遍历匹配。

解决打包jar后无法获取目录下的配置

import java.io.File;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author lingkang
 * @create by 2024/3/18 14:14
 */
public class Test04 {
    public static void main(String[] args) throws Exception {
        String scanPath = "mapper";
        List<String> result = scanResource(scanPath);
        // 输出扫描结果
        System.out.println(result);
        // 加载配置
        /*for (String config:result){
            InputStream inputStream = Test04.class.getClassLoader().getResourceAsStream(config);
        }*/
    }

    public static List<String> scanResource(String scanPath) throws Exception {
        URL url = Test04.class.getClassLoader().getResource(scanPath);
        List<String> result = new ArrayList<>();
        if (url != null) {
            JarFile jarFile = null;
            URLConnection con = url.openConnection();
            if (con instanceof JarURLConnection) {
                JarURLConnection jarCon = (JarURLConnection) con;
                jarFile = jarCon.getJarFile();
            } else {
                // 手动接收结果
                String urlFile = url.getFile();
                int separatorIndex = urlFile.indexOf("*/");// tomcat
                if (separatorIndex == -1) {
                    separatorIndex = urlFile.indexOf("!/");// jar
                }
                if (separatorIndex != -1) {
                    // String jarFileUrl = urlFile.substring(0, separatorIndex);
                    String rootEntryPath = urlFile.substring(separatorIndex + 2);  // both separators are 2 chars
                    jarFile = new JarFile(rootEntryPath);
                }
            }

            // 遍历
            if (jarFile != null) {
                boolean has = false;
                for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
                    JarEntry entry = entries.nextElement();
                    String entryPath = entry.getName();
                    // 名称匹配,可以是 ant、正则
                    if (entryPath.startsWith(scanPath)) {
                        result.add(entryPath);
                        has = true;
                    } else {
                        if (has) {
                            break;
                        }
                    }
                }
                jarFile.close();
            } else {
                // 直接遍历,此时可能是idea、eclipse开发环境。
                URL resource = Test04.class.getClassLoader().getResource("");
                if (resource != null) {
                    File file = new File(resource.getPath() + scanPath);
                    if (file.listFiles() != null)
                        for (File f : file.listFiles()) {
                            result.add(f.getPath());
                        }
                }
            }
        }
        return result;
    }
}

直接在idea运行,能正常获取到结果

image-1710744982469

打包jar再运行:

image-1710745058003

也能获取到结果,这对框架开发有所帮助。

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
打包Java项目并运行jar包,需要使用Java打包工具,如Maven或Gradle。 以下是使用Maven打包Java项目并运行jar包的步骤: 1. 在项目根目录下创建一个名为pom.xml的Maven配置文件,其中包含项目依赖和插件配置。 2. 在配置文件中添加以下插件: ```xml <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.1.2</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <mainClass>com.example.MainClass</mainClass> </manifest> </archive> </configuration> </plugin> </plugins> </build> ``` 这将生成一个可执行的jar文件,并将项目的主类指定为程序的入口点。 3. 在配置文件中添加以下依赖项: ```xml <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.10</version> </dependency> </dependencies> ``` 这将下载并包含commons-lang3库,以便您可以在程序中使用它。 4. 执行以下命令打包项目: ``` mvn package ``` 这将在target目录下生成一个名为project-name.jar的可执行文件。 5. 运行jar文件: ``` java -jar project-name.jar ``` 6. 在程序中读取properties配置文件: ```java Properties prop = new Properties(); InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties"); prop.load(input); String value = prop.getProperty("key"); ``` 在程序中可以使用Properties类读取配置文件。在这个例子中,我们可以从classpath中读取名为config.properties的配置文件,并获取其中的属性值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌康ACG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值