
- 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;
}
遍历所有类加载器,找对应资源,找到直接返回。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)