Different behavior of ClassLoader.getSystemClassLoader().getResource() in servlet container and test environment

陌路散爱 提交于 2019-12-07 16:57:47

问题


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 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.


回答1:


You can use getClass().getClassLoader().getResource(...) as an alternative to ClassLoader.getSystemClassLoader().getResource(...)

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.



来源:https://stackoverflow.com/questions/25869884/different-behavior-of-classloader-getsystemclassloader-getresource-in-servle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!