栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis源码——获取InputStream的过程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mybatis源码——获取InputStream的过程

总览
    InputStream is = Resources.getResourceAsStream(“mybatis.xml”);SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);session = factory.openSession();mapper = session.getMapper(StudentDao.class);mapper.findAll();session.commit();session.close();
正文

本文只关注第一步,看源码的方式就是按住ctrl一阵点点点。

public static InputStream getResourceAsStream(String resource) throws IOException {
  return getResourceAsStream(null, resource);
}

这里传了个null,“mybatis.xml”

public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {
  InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader);
  if (in == null) {
    throw new IOException("Could not find resource " + resource);
  }
  return in;
}

这里获取了InputStream,为空则抛异常。
很严谨,资源只有找到和没找到两种情况。

public InputStream getResourceAsStream(String resource, ClassLoader classLoader) {
  return getResourceAsStream(resource, getClassLoaders(classLoader));
}

这里应该获取了类加载器

ClassLoader[] getClassLoaders(ClassLoader classLoader) {
  return new ClassLoader[]{
      classLoader,
      defaultClassLoader,
      Thread.currentThread().getContextClassLoader(),
      getClass().getClassLoader(),
      systemClassLoader};
}

一堆类加载器:

classLoader							传入的null
defaultClassLoader					null
Thread.currentThread().getContextClassLoader()		线程提供的
getClass().getClassLoader()			当前类的
systemClassLoader					ClassLoader.getSystemClassLoader()
最终
InputStream getResourceAsStream(String resource, ClassLoader[] classLoader) {
  for (ClassLoader cl : classLoader) {
    if (null != cl) {

      // try to find the resource as passed
      InputStream returnValue = cl.getResourceAsStream(resource);

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

      if (null != returnValue) {
        return returnValue;
      }
    }
  }
  return null;
}

遍历所有类加载器,找对应资源,找到直接返回。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/715657.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号