当前位置:首页 > spring源码分析之resource
Resource相关类图
看代码过程中觉得很好的地方
AbstractResource.java
publicbooleanexists() {
// Try file existence: can we find the file in the file system? try {
return getFile().exists();
}
catch (IOException ex) {
// Fall back to stream existence: can we open the stream? try {
InputStream is = getInputStream(); is.close(); returntrue;
}
catch (Throwable isEx) { returnfalse; } } }
这段代码,面向接口编程的典范,getInputStream()是父接口定义的方法,实际上的实现是在AbstractResource的子类中实现。以一种类似于模板方法模式的方式去编程,未来可扩展性较高。
AbstractFileResolvingResource.java
/**
* Inner delegate class, avoiding a hard JBoss VFS API dependency at runtime. */
privatestaticclassVfsResourceDelegate{
publicstatic Resource getResource(URL url) throws IOException { returnnew VfsResource(VfsUtils.getRoot(url)); }
publicstatic Resource getResource(URI uri) throws IOException {
returnnew VfsResource(VfsUtils.getRoot(uri)); } }
看上面的代码的注释,目的是防止在运行时对JBoss VFS API的强依赖。说白了还是要反向依赖,依赖注入。单独看这段代码是看不出如何做到的,仔细看VfsUtils里面的代码,如下:
protectedstatic Object getRoot(URL url) throws IOException {
return invokeVfsMethod(VFS_METHOD_GET_ROOT_URL, null, url); }
// 反射调用方法
protectedstatic Object invokeVfsMethod(Method method, Object target, Object... args) throws IOException { try {
return method.invoke(target, args); }
catch (InvocationTargetException ex) {
Throwable targetEx = ex.getTargetException(); if (targetEx instanceof IOException) { throw (IOException) targetEx; }
ReflectionUtils.handleInvocationTargetException(ex); }
catch (Exception ex) {
ReflectionUtils.handleReflectionException(ex); }
thrownew IllegalStateException(\code path reached\); }
invokeVfsMethod里的method的定义如下:
// 定义静态成员变量method
privatestatic Method VFS_METHOD_GET_ROOT_URL = null; privatestatic Method VFS_METHOD_GET_ROOT_URI = null; privatestaticfinal String VFS3_PKG = \; privatestaticfinal String VFS_NAME = \;
// 通过classLoader获取类
共分享92篇相关文档