简体   繁体   中英

Load resource from the classpath of application in dependency

Essentially I have a client .jar that requires dynamic behaviour. It will need to load resources from the classpath of it's parent application. The main application is a Spring Boot application and the client .jar is a maven dependency of that project.

I find that when storing test.xml in a subfolder of src/main/resources of the Spring Boot parent project then using this code in the dependency:

InputStream fis = SSLSocketFactoryGenerator.class.getResourceAsStream("/subFolder/etc/test.xml");

will cause a null pointer as it can't find the file. Anyone know why this is and how to resolve this?

There can be 2 possible cases why you got the NPE:

1 (most likely). You incorrectly assembled your jar and it may well happen that /subFolder/etc/test.xml simply not in classpath. Take a look at ClassLoader::getResource(String name)

public URL getResource(String name) {
    URL url;
    if (parent != null) {
        url = parent.getResource(name);
    } else {
        url = getBootstrapResource(name);
    }
    if (url == null) { //not found in ClassPath, falling back to findResource.
        url = findResource(name);
    }
    return url;
}

But the "default" implementation of findResource is this:

protected URL findResource(String name) {
    return null;
}

So I would advice you to check your assembled jar-file.

2 (very unlikely). The class SSLSocketFactoryGenerator was loaded by a ClassLoader with the overriden methods for finding resources listed above. Actually I cannot imagine the case where we would override the behavoir of loading resources that are in classpath so we cannot load them. So 1. is most likely your case

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