Servlet容器和测试环境中ClassLoader.getSystemClassLoader().getResource()的不同行为 [英] Different behavior of ClassLoader.getSystemClassLoader().getResource() in servlet container and test environment
问题描述
我有一个Web应用程序,我的要求是读取一些文件并进行处理,并在应用程序启动时将文件内容保留在数据库中.
I have a web application my requirement is to read some files and process it and persist the file content in database when the application starts.
class MyUtil{
/**
*Read the files
*/
public static void readFiles(){
File file = new File(ClassLoader.getSystemClassLoader().getResource("MyFile").toURI()); //NullPointerException
// ClassLoader.getSystemClassLoader().getResource("MyFile") is giving null in servlet.init() method.
if (file.isDirectory()) {
//Read all the files and persist.
}
}
}
MyFile
文件夹/目录在类路径中可用.在JUnit测试用例中调用MyUtil.readFiles()
时,它可以正常工作.但是当在servelet.init()
方法中调用它时,ClassLoader.getSystemClassLoader().getResource("MyFile")
给出了空值.
MyFile
folder/dir is available in class path. When MyUtil.readFiles()
is called in JUnit test case it works fine. But when It's called in servelet.init()
method ClassLoader.getSystemClassLoader().getResource("MyFile")
gives the null.
推荐答案
您可以使用getClass().getClassLoader().getResource(...)
替代ClassLoader.getSystemClassLoader().getResource(...)
之所以可行,是因为在Web服务器中有多个类加载器,并且您无法确定是哪个类加载了您的类.我猜ClassLoader
类先于默认Java类加载器加载,然后MyUtil
类与Web服务器一起加载不同的类加载器,因此导致不同的类路径.
The alternative works because in webserver there are more than one class loader, and you can't be sure whichone loaded your class. I guess ClassLoader
class loaded before anything with default java class loader, and then MyUtil
class loaded with different class loader with the webserver hence it resulted in different classpath.
这篇关于Servlet容器和测试环境中ClassLoader.getSystemClassLoader().getResource()的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!