简体   繁体   中英

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

I need to load the bean XML files which is located inside another Jar file using ClassLoader. Can anyone help me here.

There are two ways to read files in other jars. These ways are suitable to application in jar mode. Please see below sample. I just read thymeleaf.properties in thymeleaf.jar file.

  1. using jdk ClassLoader
  2. using 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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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