用ClassLoader獲取資源

最近在寫Servlet的時候,看到以前的代碼裏都是這樣寫的:java

InputStream is = xxx.class.getResourceAsStream(filePath);

可是我用另外一種寫法:服務器

ClassLoader.getSystemResourceAsStream(filePath);

在本地測試的時候也是行得通的,因而把Servlet扔到服務器上,可是到了服務器上,第二種寫法就跑不通了。今天找到了下面這個文章:測試

    

ClassLoader.getSystemResourceAsStream and this.getClass().getClassLoader().getResourceAsStream()  


ClassLoader.getSystemResourceAsStream uses the system ClassLoader (ClassLoader.getSystemClassLoader) to search for the resource.
this.getClass().getClassLoader().getResourceAsStream() uses the same ClassLoader that loaded the class for "this" Object. That ClassLoader might be a child of the system ClassLoader, and thus could have access to resources the system ClassLoader does not have. But since it is a child of the System ClassLoader, it also will ask its parent (System) to help it find resources. So using this method will allow you to find things in that ClassLoader AND in the System ClassLoader.
The search order is defined in the javadoc for ClassLoader.getResource (parent(s) first, then child).
For example, say you were running some code from a Servlet. The System ClassLoader contains whatever you put in CLASSPATH when you started the Web Server, but the servlet class is probably loaded by another ClassLoader that the server created to handle the WebApp's WEB-INF/lib and WEB-INF/classes directories. Things in those directories would be accessible using that WebApp's ClassLoader, but would not be in CLASSPATH - so the System ClassLoader does not know about them.
I'm not sure I explained that well - hope it helps.

So if you want to get properties from a static method, it's better to use:
SomeClass.class.getClassLoader().getResourceAsStream("XX.properties"));this


文章的地址:http://yaodong.yu.blog.163.com/blog/static/121426690200961282221588/spa

相關文章
相關標籤/搜索