一、ClassLoaderWrapper与Resources
1、ClassLoaderWrapper
? ? ClassLoader是用来加载资源的,也是面试经常提及的一个点,其中涉及类的加载机制双亲委派模式,感兴趣的读者可以自行了解一下。
? ? 在MyBatis的IO包中,ClassLoaderWrapper封装了ClassLoader以及读取资源文件的相关API。通过调整多个类加载器的使用顺序,它可以确保返回给系统使用的是正确的类加载器。使用ClassLoaderWrapper就像使用ClassLoader对象,ClassLoaderWrapper会按照指定的顺序依次检测其中封装的ClassLoader对象,并从中选取第一个可用的ClassLoader完成相关功能。
? ? ClassLoaderWrapper的主要功能可以分为三类:getResourceAsURL()方法、getResourceAsStream()方法、classForName()方法,这3个方法都有多个重载,最终底层都会调用参数为String和ClassLoader[]的重载。而前面两个方法的的底层是ClassLoader的getResource()与getResourceAsStream()方法,上一节中我们用到了getResourceAsStream()方法,我们多多少少还是有点感觉的。当然ClassLoader源码里面不仅仅只有这两个方法,还有其他的感兴趣的童鞋可以看看源码;classForName()方法的底层就是Class.forName()方法。
? ? getResource()返回值为URL类型,getResourceAsStream()返回值是InputStream类型。
? ? 由于一些配置文件的数据结构简单,可以直接将InputStream数据流转换为Map结构数据Properties;而有些数据结构比较复杂,xml形式的配置文件往往是一种树形结构的,故中间还得经过加工转换为树形结构数据,这就是配置文件的解析过程进行处理的,将在后面章节介绍。
2、Resources
? ? Resources顾名思义就是资源的意思,是MyBatis提供了多个静态方法的工具类,有些方法中做了一些异常的处理。为满足多样的需求,在Resources里面对ClassLoaderWrapper进行了封装,提供了方法的多种重载以满足多样的需求。
Resources一般使用的场景:
从类路径加载 SQL Map 配置文件(如 sqlMap-config.xml) 从类路径加载 mapper配置文件(如 XXXMapper.xml) 从类路径加载各种.properties 文件
Resources使用的几种方法:
对于简单的只读文本数据,加载为 Reader 对于简单的只读二进制或文本数据,加载为 Stream 对于可读写的二进制或文本文件,加载为 File 对于只读的配置属性文件,加载为 Properties 对于只读的通用资源,加载为 URL
二、测试举例
MyBatis的ResourcesTest其实已经提供给了一些使用测试示例,实际上跟MyBatis是如何加载配置文件的1的回顾里面代码是同样的理论。
public class ResourcesTest extends BaseDataTest {
private static final ClassLoader CLASS_LOADER = ResourcesTest.class.getClassLoader();
@Test
public void shouldGetUrlForResource() throws Exception {
URL url = Resources.getResourceURL(JPETSTORE_PROPERTIES);
assertTrue(url.toString().endsWith("jpetstore/jpetstore-hsqldb.properties"));
}
@Test
public void shouldGetUrlAsProperties() throws Exception {
URL url = Resources.getResourceURL(CLASS_LOADER, JPETSTORE_PROPERTIES);
Properties props = Resources.getUrlAsProperties(url.toString());
assertNotNull(props.getProperty("driver"));
}
}
三、源码
1、ClassLoaderWrapper
/**
* A class to wrap access to multiple class loaders making them work as one
*
* @author Clinton Begin
*/
public class ClassLoaderWrapper {
ClassLoader defaultClassLoader;
ClassLoader systemClassLoader;
ClassLoaderWrapper() {
try {
systemClassLoader = ClassLoader.getSystemClassLoader();
} catch (SecurityException ignored) {
// AccessControlException on Google App Engine
}
}
/**
* Get a resource as a URL using the current class path
*
* @param resource - the resource to locate
* @return the resource or null
*/
public URL getResourceAsURL(String resource) {
return getResourceAsURL(resource, getClassLoaders(null));
}
/**
* Get a resource from the classpath, starting with a specific class loader
*
* @param resource - the resource to find
* @param classLoader - the first classloader to try
* @return the stream or null
*/
public URL getResourceAsURL(String resource, ClassLoader classLoader) {
return getResourceAsURL(resource, getClassLoaders(classLoader));
}
/**
* Get a resource from the classpath
*
* @param resource - the resource to find
* @return the stream or null
*/
public InputStream getResourceAsStream(String resource) {
return getResourceAsStream(resource, getClassLoaders(null));
}
/**
* Get a resource from the classpath, starting with a specific class loader
*
* @param resource - the resource to find
* @param classLoader - the first class loader to try
* @return the stream or null
*/
public InputStream getResourceAsStream(String resource, ClassLoader classLoader) {
return getResourceAsStream(resource, getClassLoaders(classLoader));
}
/**
* Find a class on the classpath (or die trying)
*
* @param name - the class to look for
* @return - the class
* @throws ClassNotFoundException Duh.
*/
public Class<?> classForName(String name) throws ClassNotFoundException {
return classForName(name, getClassLoaders(null));
}
/**
* Find a class on the classpath, starting with a specific classloader (or die trying)
*
* @param name - the class to look for
* @param classLoader - the first classloader to try
* @return - the class
* @throws ClassNotFoundException Duh.
*/
public Class<?> classForName(String name, ClassLoader classLoader) throws ClassNotFoundException {
return classForName(name, getClassLoaders(classLoader));
}
/**
* Try to get a resource from a group of classloaders
*
* @param resource - the resource to get
* @param classLoader - the classloaders to examine
* @return the resource or null
*/
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;
}
/**
* Get a resource as a URL using the current class path
*
* @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;
}
/**
* Attempt to load a class from a group of classloaders
*
* @param name - the class to load
* @param classLoader - the group of classloaders to examine
* @return the class
* @throws ClassNotFoundException - Remember the wisdom of Judge Smails:
* Well, the world needs ditch diggers, too.
*/
Class<?> classForName(String name, ClassLoader[] classLoader) throws ClassNotFoundException {
for (ClassLoader cl : classLoader) {
if (null != cl) {
try {
Class<?> c = Class.forName(name, true, cl);
if (null != c) {
return c;
}
} catch (ClassNotFoundException e) {
// we'll ignore this until all classloaders fail to locate the class
}
}
}
throw new ClassNotFoundException("Cannot find class: " + name);
}
ClassLoader[] getClassLoaders(ClassLoader classLoader) {
return new ClassLoader[]{
classLoader,
defaultClassLoader,
Thread.currentThread().getContextClassLoader(),
getClass().getClassLoader(),
systemClassLoader};
}
}
2、Resources
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Properties;
/**
* A class to simplify access to resources through the classloader.
*
* @author Clinton Begin
*/
public class Resources {
private static ClassLoaderWrapper classLoaderWrapper = new ClassLoaderWrapper();
/**
* Charset to use when calling getResourceAsReader.
* null means use the system default.
*/
private static Charset charset;
Resources() {
}
/**
* Returns the default classloader (may be null).
*
* @return The default classloader
*/
public static ClassLoader getDefaultClassLoader() {
return classLoaderWrapper.defaultClassLoader;
}
/**
* Sets the default classloader
*
* @param defaultClassLoader - the new default ClassLoader
*/
public static void setDefaultClassLoader(ClassLoader defaultClassLoader) {
classLoaderWrapper.defaultClassLoader = defaultClassLoader;
}
/**
* Returns the URL of the resource on the classpath
*
* @param resource The resource to find
* @return The resource
* @throws java.io.IOException If the resource cannot be found or read
*/
public static URL getResourceURL(String resource) throws IOException {
// issue #625
return getResourceURL(null, resource);
}
/**
* Returns the URL of the resource on the classpath
*
* @param loader The classloader used to fetch the resource
* @param resource The resource to find
* @return The resource
* @throws java.io.IOException If the resource cannot be found or read
*/
public static URL getResourceURL(ClassLoader loader, String resource) throws IOException {
URL url = classLoaderWrapper.getResourceAsURL(resource, loader);
if (url == null) {
throw new IOException("Could not find resource " + resource);
}
return url;
}
/**
* Returns a resource on the classpath as a Stream object
*
* @param resource The resource to find
* @return The resource
* @throws java.io.IOException If the resource cannot be found or read
*/
public static InputStream getResourceAsStream(String resource) throws IOException {
return getResourceAsStream(null, resource);
}
/**
* Returns a resource on the classpath as a Stream object
*
* @param loader The classloader used to fetch the resource
* @param resource The resource to find
* @return The resource
* @throws java.io.IOException If the resource cannot be found or read
*/
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;
}
/**
* Returns a resource on the classpath as a Properties object
*
* @param resource The resource to find
* @return The resource
* @throws java.io.IOException If the resource cannot be found or read
*/
public static Properties getResourceAsProperties(String resource) throws IOException {
Properties props = new Properties();
try (InputStream in = getResourceAsStream(resource)) {
props.load(in);
}
return props;
}
/**
* Returns a resource on the classpath as a Properties object
*
* @param loader The classloader used to fetch the resource
* @param resource The resource to find
* @return The resource
* @throws java.io.IOException If the resource cannot be found or read
*/
public static Properties getResourceAsProperties(ClassLoader loader,
String resource) throws IOException {
Properties props = new Properties();
try (InputStream in = getResourceAsStream(loader, resource)) {
props.load(in);
}
return props;
}
/**
* Returns a resource on the classpath as a Reader object
*
* @param resource The resource to find
* @return The resource
* @throws java.io.IOException If the resource cannot be found or read
*/
public static Reader getResourceAsReader(String resource) throws IOException {
Reader reader;
if (charset == null) {
reader = new InputStreamReader(getResourceAsStream(resource));
} else {
reader = new InputStreamReader(getResourceAsStream(resource), charset);
}
return reader;
}
/**
* Returns a resource on the classpath as a Reader object
*
* @param loader The classloader used to fetch the resource
* @param resource The resource to find
* @return The resource
* @throws java.io.IOException If the resource cannot be found or read
*/
public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException {
Reader reader;
if (charset == null) {
reader = new InputStreamReader(getResourceAsStream(loader, resource));
} else {
reader = new InputStreamReader(getResourceAsStream(loader, resource), charset);
}
return reader;
}
/**
* Returns a resource on the classpath as a File object
*
* @param resource The resource to find
* @return The resource
* @throws java.io.IOException If the resource cannot be found or read
*/
public static File getResourceAsFile(String resource) throws IOException {
return new File(getResourceURL(resource).getFile());
}
/**
* Returns a resource on the classpath as a File object
*
* @param loader - the classloader used to fetch the resource
* @param resource - the resource to find
* @return The resource
* @throws java.io.IOException If the resource cannot be found or read
*/
public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException {
return new File(getResourceURL(loader, resource).getFile());
}
/**
* Gets a URL as an input stream
*
* @param urlString - the URL to get
* @return An input stream with the data from the URL
* @throws java.io.IOException If the resource cannot be found or read
*/
public static InputStream getUrlAsStream(String urlString) throws IOException {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
return conn.getInputStream();
}
/**
* Gets a URL as a Reader
*
* @param urlString - the URL to get
* @return A Reader with the data from the URL
* @throws java.io.IOException If the resource cannot be found or read
*/
public static Reader getUrlAsReader(String urlString) throws IOException {
Reader reader;
if (charset == null) {
reader = new InputStreamReader(getUrlAsStream(urlString));
} else {
reader = new InputStreamReader(getUrlAsStream(urlString), charset);
}
return reader;
}
/**
* Gets a URL as a Properties object
*
* @param urlString - the URL to get
* @return A Properties object with the data from the URL
* @throws java.io.IOException If the resource cannot be found or read
*/
public static Properties getUrlAsProperties(String urlString) throws IOException {
Properties props = new Properties();
try (InputStream in = getUrlAsStream(urlString)) {
props.load(in);
}
return props;
}
/**
* Loads a class
*
* @param className - the class to fetch
* @return The loaded class
* @throws ClassNotFoundException If the class cannot be found (duh!)
*/
public static Class<?> classForName(String className) throws ClassNotFoundException {
return classLoaderWrapper.classForName(className);
}
public static Charset getCharset() {
return charset;
}
public static void setCharset(Charset charset) {
Resources.charset = charset;
}
}
|