使用
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
解读
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
getResourceAsStream-1
public static InputStream getResourceAsStream(String resource) throws IOException {
return getResourceAsStream(null, resource);
}
getResourceAsStream-2
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;
}
这里就是通过ClassLoader获取资源
Resources中classLoaderWrapper定义
public class Resources {
// classLoader的封装
private static ClassLoaderWrapper classLoaderWrapper = new ClassLoaderWrapper();
ClassLoaderWrapper
public class ClassLoaderWrapper {
ClassLoader defaultClassLoader;
ClassLoader systemClassLoader;
ClassLoaderWrapper() {
try {
systemClassLoader = ClassLoader.getSystemClassLoader();
} catch (SecurityException ignored) {
// AccessControlException on Google App Engine
}
}
就是声明2个ClassLoader 并初始化一个systemClassLoader另一个 不初始化
InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader);这个方法
public InputStream getResourceAsStream(String resource) {
return getResourceAsStream(resource, getClassLoaders(null));
}
getClassLoaders
ClassLoader[] getClassLoaders(ClassLoader classLoader) {
return new ClassLoader[]{
classLoader,
defaultClassLoader,
Thread.currentThread().getContextClassLoader(),
getClass().getClassLoader(),
systemClassLoader};
}
getClassLoaders方法获取一个ClassLoader数组
getResourceAsStream(resource, getClassLoaders(null));
InputStream getResourceAsStream(String resource, ClassLoader[] classLoader) {
for (ClassLoader cl : classLoader) {
if (null != cl) {
//将指定路径的资源文转换为流
InputStream returnValue = cl.getResourceAsStream(resource);
//如果找不到就去根路径下找
if (null == returnValue) {
returnValue = cl.getResourceAsStream("/" + resource);
}
if (null != returnValue) {
return returnValue;
}
}
}
return null;
}
总结
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
就是通过ClassLoader的方法将传入资源文件解析为指定流或者其它