0.1 、Spring 源码学习-JVM类加载器-双亲委派模型-Spring 中类加载机制

本文深入探讨了Spring框架中类加载机制的实现细节,包括AbstractApplicationContext.prepareBeanFactory方法的作用,DefaultResourceLoader如何获取类加载器,以及ClassUtils.getDefaultClassLoader方法的具体逻辑。同时,文章还讨论了Java类加载器的基本概念和双亲委派模型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Java 类加载器的介绍

JVM-类加载器、双亲委派模型、自定义类加载器

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 (类加载机制)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值