簡體   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