对mybatis源码进行一次分析,特此记录
根据mybatis框架和mybatis案例分析
第一步:会加载配置文件输入流
1 String resource="mybatis-config.xml"; 2 InputStream inputStream=Resources.getResourceAsStream(resource);
Resources.getResourceAsStream(resource)方法源码为:
1 /* 2 * Returns a resource on the classpath as a Stream object 3 * 4 * @param resource The resource to find 5 * @return The resource 6 * @throws java.io.IOException If the resource cannot be found or read 7 */ 8 public static InputStream getResourceAsStream(String resource) throws IOException { 9 return getResourceAsStream(null, resource); 10 } 11 12 /* 13 * Returns a resource on the classpath as a Stream object 14 * 15 * @param loader The classloader used to fetch the resource 16 * @param resource The resource to find 17 * @return The resource 18 * @throws java.io.IOException If the resource cannot be found or read 19 */ 20 public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException { 21 InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader); 22 if (in == null) { 23 throw new IOException("Could not find resource " + resource); 24 } 25 return in; 26 }
再通过这一行语句InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader);获取输入流信息,其中类加载器包装类
1 /* 2 * Get a resource from the classpath, starting with a specific class loader 3 * 4 * @param resource - the resource to find 5 * @param classLoader - the first class loader to try 6 * @return the stream or null 7 */ 8 public InputStream getResourceAsStream(String resource, ClassLoader classLoader) { 9 return getResourceAsStream(resource, getClassLoaders(classLoader)); 10 }
定义类加载器顺序
1 ClassLoader[] getClassLoaders(ClassLoader classLoader) { 2 return new ClassLoader[]{ 3 //参数指定的类加载器 4 classLoader, 5 //系统指定的默认类加载器 6 defaultClassLoader, 7 //当前线程绑定的类加载器 8 Thread.currentThread().getContextClassLoader(), 9 //当前类使用的类加载器 10 getClass().getClassLoader(), 11 // 系统的类加载器 12 systemClassLoader}; 13 }
1 /* 2 * Try to get a resource from a group of classloaders 3 * 4 * @param resource - the resource to get 5 * @param classLoader - the classloaders to examine 6 * @return the resource or null 7 */ 8 InputStream getResourceAsStream(String resource, ClassLoader[] classLoader) { 9 //从指定的资源(resource资源的URL) 按顺序(ClassLoader[]中的顺序)加载,加载到开始返回 10 for (ClassLoader cl : classLoader) { 11 if (null != cl) { 12 13 // try to find the resource as passed 14 InputStream returnValue = cl.getResourceAsStream(resource); 15 16 // now, some class loaders want this leading "/", so we'll add it and try again if we didn't find the resource 17 if (null == returnValue) { 18 returnValue = cl.getResourceAsStream("/" + resource); 19 } 20 21 if (null != returnValue) { 22 return returnValue; 23 } 24 } 25 } 26 return null; 27 }