文档详情

spring源码分析之resource.docx

发布:2016-12-13约5.17千字共8页下载文档
文本预览下载声明
Resource相关类图看代码过程中觉得很好的地方AbstractResource.java public boolean exists() { // 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(); return true; } catch (Throwable isEx) { return false; } } }这段代码,面向接口编程的典范,getInputStream()是父接口定义的方法,实际上的实现是在AbstractResource的子类中实现。以一种类似于模板方法模式的方式去编程,未来可扩展性较高。AbstractFileResolvingResource.java /** * Inner delegate class, avoiding a hard JBoss VFS API dependency at runtime. */ private static class VfsResourceDelegate { public static Resource getResource(URL url) throws IOException { return new VfsResource(VfsUtils.getRoot(url)); } public static Resource getResource(URI uri) throws IOException { return new VfsResource(VfsUtils.getRoot(uri)); } }看上面的代码的注释,目的是防止在运行时对JBoss VFS API的强依赖。说白了还是要反向依赖,依赖注入。 单独看这段代码是看不出如何做到的,仔细看VfsUtils里面的代码,如下: protected static Object getRoot(URL url) throws IOException { return invokeVfsMethod(VFS_METHOD_GET_ROOT_URL, null, url); } // 反射调用方法 protected static 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); } throw new IllegalStateException(Invalid code path reached); }invokeVfsMethod里的method的定义如下: // 定义静态成员变量method private static Method VFS_METHOD_GET_ROOT_URL = null; private static Method VFS_METHOD_GET_ROOT_URI = null; private static final String VFS3_PKG = org.jboss.vfs.; private static final String VFS_NAME = VFS; // 通过classLoader获取类 Class? vfsClass = loader.loadClass(VFS3_PKG + VFS_NAME); // 反射获取method VFS_METHOD_GET_ROOT_URL = ReflectionUtils.findMethod(vfsClass, getChild, U
显示全部
相似文档