开发者

Reloading resources loaded by getResourceAsStream

开发者 https://www.devze.com 2023-02-05 13:26 出处:网络
Following best practices, I\'m using Thread.currentThread().getContextClassLoader().getResourceAsStream to load resources in a web application (like text files or xml files), instead of going through

Following best practices, I'm using Thread.currentThread().getContextClassLoader().getResourceAsStream to load resources in a web application (like text files or xml files), instead of going through the file API.

However, this has the disadvantage that if the resource chan开发者_运维知识库ges on disk, a following call to getResourceAsStream keeps returning the old version indefinitely.

I would like it to pick up the new version though. In my debugger I see there's a simple HashMap called resourceEntries in the classLoader. Using reflection I've been able to remove a specific entry and this seems to work.

This method is however fragile.

Is there a more standard way to do this?


Try this:

ClassLoader ctxLoader = Thread.currentThread().getContextClassLoader();
URL resURL = ctxLoader.getResource(resName);
URLConnection resConn = resURL.openConnection();
resConn.setUseCaches(false);
InputStream resIn = resConn.getInputStream();
...


In addition to kschneid's answer which might work for Tomcat indeed, I wanted to add that for JBoss AS 5+ it already seems to work without needing any special tricks.

Caching of resources is probably class loader specific. The JBoss AS one either doesn't cache or is smart enough to see that the resource on disk has changed.


i finally solved this problem by change the jar file name, every time i change the resource content, i change a new name with current timestamp

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号