Mybatis原理分析之七:资源加载

包结构

Mybatis原理分析之七:资源加载_第1张图片

本包主要包含了资源加载和访问相关的类。

一 VFS类介绍

 作用:

虚拟文件系统(VFS),用来读取服务器里的资源
提供了2个实现 JBoss6VFS 和 DefaultVFS,并提供了用户扩展点,可定义VFS实现

加载顺序: 自定义VFS实现 > 默认VFS实现 取第一个加载成功的

添加用户VFS实现

public static void addImplClass(Classextends VFS> clazz) {
  if (clazz != null) {
    USER_IMPLEMENTATIONS.add(clazz);
  }
}

二 ClassLoaderWrapper

封装了5个类加载器,getClassLoaders方法

//一共5个类加载器
ClassLoader[] getClassLoaders(ClassLoader classLoader) {
  return new ClassLoader[]{
      classLoader,
      defaultClassLoader,
      Thread.currentThread().getContextClassLoader(),
      getClass().getClassLoader(),
      systemClassLoader};
}
类加载器查找资源

/*
 * Get a resource as a URL using the current class path
 * 用5个类加载器一个个查找资源,只要其中任何一个找到,就返回
 *
 * @param resource    - the resource to locate
 * @param classLoader - the class loaders to examine
 * @return the resource or null
 */
URL getResourceAsURL(String resource, ClassLoader[] classLoader) {

  URL url;

  for (ClassLoader cl : classLoader) {

    if (null != cl) {

      // look for the resource as passed in...
      url = cl.getResource(resource);

      // ...but some class loaders want this leading "/", so we'll add it
      // and try again if we didn't find the resource
      if (null == url) {
        url = cl.getResource("/" + resource);
      }

      // "It's always in the last place I look for it!"
      // ... because only an idiot would keep looking for it after finding it, so stop looking already.
      if (null != url) {
        return url;
      }

    }

  }

  // didn't find it anywhere.
  return null;

}




你可能感兴趣的:(Mybatis)