Resource Components of Spring

1.资源组件UML类图
Resource Components of Spring_第1张图片
资源组件接口中核心方法:exists(), isopen(), isReadable(), getInputStream()
引用核心的Java API:File类,URL类
2.重点介绍UrlResource和ClasspathResource
UrlResource
     利用统一资源标识符或者定位符加载资源,其中UrlResource封装了Url,UrlConnection的操作。持有Url,Uri等对象。UrlResource的exists(), isReadable()方法继承自父类AbstractResourceResolving。提供了利用Url变量得到文件File。用File类的方法操作资源,验证资源的可读性,是否存在,是否可被打开!通过UrlConnection获取资源的输入流!
例如:
public InputStream getInputStream() throws IOException {
URLConnection con = this. url.openConnection();
ResourceUtils.useCachesIfNecessary( con);
try {
return con.getInputStream();
}
catch (IOException ex) {
// Close the HTTP connection (if applicable).
if ( con instanceof HttpURLConnection) {
((HttpURLConnection) con).disconnect();
}
throw ex;
}
}

ClassPathResource
此对象用来获取class path下的资源,其中ClassPathResource持有Class, ClassLoader等对象。利用Class和ClassLoader对象的getResource()和getResourceStream()方法操作资源,妥妥的!
例如:
判断资源是否存在
public boolean exists() {
return (resolveURL() != null);
 }

protected URL resolveURL() {
if ( this. clazz != null) {
return this. clazz.getResource( this. path);
}
else if ( this. classLoader != null) {
return this. classLoader.getResource( this. path);
}
else {
return ClassLoader.getSystemResource( this. path);
}
}



获取资源的输入流对象
public InputStream getInputStream() throws IOException {
InputStream is;
if ( this. clazz != null) {
is = this. clazz.getResourceAsStream( this. path);
}
else if ( this. classLoader != null) {
is = this. classLoader.getResourceAsStream( this. path);
}
else {
is = ClassLoader.getSystemResourceAsStream( this. path);
}
if ( is == null) {
throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
}
return is;

}


你可能感兴趣的:(Spring,FrameWork)