繁体   English   中英

如何使用 ClassLoader 从另一个 jar 加载 bean XML 文件

[英]How to load the bean XML file from another jar using ClassLoader

我需要使用 ClassLoader 加载位于另一个 Jar 文件中的 bean XML 文件。 有人能帮我一下吗。

其他jars中的文件有两种读取方式。 这些方式适用于 jar 模式下的应用。 请参阅下面的示例。 我刚刚阅读了 thymeleaf.jar 文件中的 thymeleaf.properties。

  1. 使用 jdk 类加载器
  2. 使用 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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM