如何使用classloader从另一个jar加载bean xml文件

busg9geu  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(321)

我需要使用classloader加载位于另一个jar文件中的bean xml文件。有人能帮我吗。

oxiaedzo

oxiaedzo1#

有两种方法可以读取其他jar中的文件。这些方法适用于jar模式的应用。请看下面的样品。我刚刚读取了thymeleaf.jar文件中的thymeleaf.properties。
使用jdk类加载器
使用spring pathmatchingresourcepatternresolver

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MyService  {

    public static void printInfo() throws Exception {
        InputStream fis = MyService.class.getClassLoader().getResourceAsStream("org/thymeleaf/thymeleaf.properties");
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        String s = "";
        while ((s = br.readLine()) != null){
            System.out.println(s);
        }
        br.close();

        PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = patternResolver.getResources("org/thymeleaf/thymeleaf.properties");
        if (resources != null && resources.length > 0) {
            br = new BufferedReader(new InputStreamReader(resources[0].getInputStream()));
            s = "";
            while ((s = br.readLine()) != null){
                System.out.println(s);
            }
            br.close();
        }

    }

    public static void main(String[] args) throws Exception {
        printInfo();
    }
}

相关问题