spring_ClassPathResource中的获取classpath资源实现

一、核心代码

* This implementation opens an InputStream for the given class path resource.
* @see java.lang.ClassLoader#getResourceAsStream(String)
* @see java.lang.Class#getResourceAsStream(String)
*/
public InputStream getInputStream() throws IOException {
InputStream is;
if (this.clazz != null) {
is = this.clazz.getResourceAsStream(this.path);
}
else {
is = this.classLoader.getResourceAsStream(this.path);
}
if (is == null) {
throw new FileNotFoundException(
getDescription() + " cannot be opened because it does not exist");
}
return is;
}
 

二、逻辑:

逻辑 写道
1.如果有传入一个类,将用该类的Class.getResourceAsStream来加载资源;
2.如果null则用ClassLoader来加载资源;
ClassLoader在ClassPathResource中已避免走它为null的情况,具体可以看构造方法,结合第一个分支判断。

说明:
1.Class.getResourceAsStream和ClassLoader.getResourceAsStream有区别。具体区别体现在Class.getResourceAsStream的name = resolveName(name);
2.ClassPathResource的public ClassPathResource(String path, ClassLoader classLoader)构造方法很有意思,可以看看;

三、 仔细研究可以有以下收获:

1.Java的ClassLoader知识体系;

2.Spring加载classpath资源的方式;

一些资料参考:

1.Java的ClassLoader知识体系:

http://zddava.iteye.com/blog/258900

http://blog.csdn.net/changewang/article/details/6107507

http://www.blogjava.net/lihuaxajh/articles/94371.html

http://blog.csdn.net/zhouysh/article/details/5889564

http://www.qqread.com/java/2010/03/w492173.html

2.Spring加载classpath资源的方式:

参考ClassPathResource和ClassUtils

猜你喜欢

转载自simple56.iteye.com/blog/1354195
今日推荐