文章目录
文章目录
1、Java 类加载器的介绍
2、Spring 类加载机制
2.1、 入口 AbstractApplicationContext.prepareBeanFactory
beanFactory.setBeanClassLoader(getClassLoader());
2.2、DefaultResourceLoader.getClassLoader()
org.springframework.core.io.DefaultResourceLoader
/**
* Return the ClassLoader to load class path resources with.
* <p>Will get passed to ClassPathResource's constructor for all
* ClassPathResource objects created by this resource loader.
* @see ClassPathResource
*/
@Override
public ClassLoader getClassLoader() {
//如果指定了类加载器就返回指定的类加载器,否则获取线程类加载器->不存在就获取ClassUtils类加载器-> 不存在就获取系统默认类加载器
return (this.classLoader != null ? this.classLoader : ClassUtils.getDefaultClassLoader());
}
2.3、ClassUtils.getDefaultClassLoader()
org.springframework.util.ClassUtils.getDefaultClassLoader()
看中文注释
/**
* Return the default ClassLoader to use: typically the thread context
* ClassLoader, if available; the ClassLoader that loaded the ClassUtils
* class will be used as fallback.
* <p>Call this method if you intend to use the thread context ClassLoader
* in a scenario where you clearly prefer a non-null ClassLoader reference:
* for example, for class path resource loading (but not necessarily for
* {@code Class.forName}, which accepts a {@code null} ClassLoader
* reference as well).
* @return the default ClassLoader (only {@code null} if even the system
* ClassLoader isn't accessible)
* @see Thread#getContextClassLoader()
* @see ClassLoader#getSystemClassLoader()
*/
public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null;
try {
//获取当前线程类加载器
cl = Thread.currentThread().getContextClassLoader();
}
catch (Throwable ex) {
// Cannot access thread context ClassLoader - falling back...
}
//如果线程类加载器为null
if (cl == null) {
// No thread context class loader -> use class loader of this class.
//获取当前类的类加载器
cl = ClassUtils.class.getClassLoader();
if (cl == null) {
// getClassLoader() returning null indicates the bootstrap ClassLoader
//getClassLoader() 为 null 说明是 bootstrap ClassLoader 类加载器,该加载器为 C++ 编写,故从Java 角度看是 null
try {
//获取当前系统的类加载器
cl = ClassLoader.getSystemClassLoader();
}
catch (Throwable ex) {
// Cannot access system ClassLoader - oh well, maybe the caller can live with null...
}
}
}
return cl;
}
3、延伸阅读:破坏双亲委派模型
tomcat 其实遵循了标准的双亲委派模型,但是其在能力扩展上,违背了双亲委派模型
Tomcat 类加载器之为何违背双亲委派模型
参考资料
[1]、https://www.jianshu.com/p/554c138ca0f5 (类加载机制)