Spring源码十五:Bean的加载

news2024/10/6 12:16:14

上一篇我们通过Spring源码十四:Spring生命周期介绍了refresh的最后两个方法,至此通过前面大概十篇左右的篇幅介绍完了Spring容器初始化,接下来,将进入Spring另外一个模块Bean相关的知识点。

在Spring框架中,Bean加载过程是一个复杂且至关重要的环节。在这一节的内容中,我们将探讨如何从BeanDefinition实例化一个Bean,并了解Spring在ApplicationContext初始化时的一些高级特性在Bean加载过程中如何发挥作用。下面是我们的分析步骤:


回到我们最开始的示例代码如下:

package org.springframework;

import org.springframework.ApplicationContext.MyselfClassPathXmlApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.dto.JmUser;
import org.springframework.event.MyselfEvent;

/**
 * @author Jeremy
 * @version 1.0
 * @description: 主方法
 * @date 2024/6/30 02:58
 */
public class Main {
	public static void main(String[] args) {
		ApplicationContext context = new MyselfClassPathXmlApplicationContext("applicationContext.xml");
		JmUser jmUser = (JmUser)context.getBean("jmUser");
//		System.out.println(jmUser.getName());
//		System.out.println(jmUser.getAge());
		// 发布事件
		MyselfEvent event = new MyselfEvent("事件源:source", "This is a custom event");
		context.publishEvent(event);


	}
}

到目前我们为止,咱们知识跟踪了:

ApplicationContext context = new MyselfClassPathXmlApplicationContext("applicationContext.xml");

这一段代码接下来我们看下面的方法:


getBean

判断Spring容器是否激活和关闭,如果测试容器还未激活或者已经关闭则直接抛出异常。毕竟Spring中的bean都是存在容器中的,容器都没有了到哪儿获取bean呢?

接着往下看,通过getBeanFactory先获取到容器,返回的是DefaultListableBeanFactory,前面有分析过它的类图,这里就展开了,在执行的getBeanFactory方法的时候,我特意将BeanDefinitionNames属性展开了,可以这个名字很熟悉。在给大家看下我们的xml配置,这下是不是就很熟悉了呢:

铺垫了这么多就是为了让大家将前面的内容给串联起来,我们在Spring中的每个配置最终都会转化成Spring容器中的属性。好了接下来我们开始正式进入getBean方法。


看到我们进入了BeanFactory的getBean方法,这个时候回去调用doGetBean方法。在Spring中但凡看到do作为前缀的一定要留一个心眼,基本上是真正处理逻辑的地方。

进入doGetBean方法一探究竟:


doGetBean

/**
	 * Return an instance, which may be shared or independent, of the specified bean.
	 * @param name the name of the bean to retrieve
	 * @param requiredType the required type of the bean to retrieve
	 * @param args arguments to use when creating a bean instance using explicit arguments
	 * (only applied when creating a new instance as opposed to retrieving an existing one)
	 * @param typeCheckOnly whether the instance is obtained for a type check,
	 * not for actual use
	 * @return an instance of the bean
	 * @throws BeansException if the bean could not be created
	 */
	@SuppressWarnings("unchecked")
	protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

		// 获取转换后的Bean名称
		final String beanName = transformedBeanName(name);
		Object bean;

		// Eagerly check singleton cache for manually registered singletons.
		// 检查单例缓存中是否有手动注册的单例Bean
		Object sharedInstance = getSingleton(beanName);
		// 如果单缓存中存在则直接从缓存中获取,
		// 如果不存在就走else分支,进行实例化
		if (sharedInstance != null && args == null) {
			if (logger.isTraceEnabled()) {
				if (isSingletonCurrentlyInCreation(beanName)) {
					logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
							"' that is not fully initialized yet - a consequence of a circular reference");
				}
				else {
					logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
				}
			}
			// 获取Bean的实例对象
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
			// 如果当前bean还未被实例化,则在这个判断中准备实例化
			// Fail if we're already creating this bean instance:
			// We're assumably within a circular reference.
			// 如果bean的类型是prototype且正在创建,直接抛出异常
			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			// Check if bean definition exists in this factory.
			// 检查Bean定义是否存在于当前工厂
			/// 获取容器的父容器
			BeanFactory parentBeanFactory = getParentBeanFactory();
			// 存在父容器,且当前容器没有beanName的BeanDefinition,则通过父容器获取bean
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
				// Not found -> check parent.
				String nameToLookup = originalBeanName(name);
				if (parentBeanFactory instanceof AbstractBeanFactory) {
					return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
							nameToLookup, requiredType, args, typeCheckOnly);
				}
				else if (args != null) {
					// Delegation to parent with explicit args.
					return (T) parentBeanFactory.getBean(nameToLookup, args);
				}
				else if (requiredType != null) {
					// No args -> delegate to standard getBean method.
					return parentBeanFactory.getBean(nameToLookup, requiredType);
				}
				else {
					return (T) parentBeanFactory.getBean(nameToLookup);
				}
			}

			if (!typeCheckOnly) {
				// 标记bean已经开始创建,其实就是将当前beanName 放入alreadyCreated容器中
				markBeanAsCreated(beanName);
			}

			// 进入实例化bean阶段
			try {
				// 合并容器中beanName对应的BeanDefinition,得到新的root类型BeanDefinition
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				// 校验合并后的rootBeanDefinition是否达到实例化标准,abstractFlag默认是false,如果是true则抛出异常
				checkMergedBeanDefinition(mbd, beanName, args);

				// Guarantee initialization of beans that the current bean depends on.
				// 获取当前beanName所依赖的BeanNames数组
				String[] dependsOn = mbd.getDependsOn();
				// 如果依赖的bean不为空,则注册这些bean且递归调用getBean,提前实例化需要依赖的Bean
				if (dependsOn != null) {
					for (String dep : dependsOn) {
						if (isDependent(beanName, dep)) {
							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
									"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
						}
						// 注册依赖的bean
						registerDependentBean(dep, beanName);
						try {
							// 递归调用getBean,需要依赖的Bean先实例化
							getBean(dep);
						}
						catch (NoSuchBeanDefinitionException ex) {
							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
									"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
						}
					}
				}

				// Create bean instance.
				// 判断beanDefinition是单例?
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, () -> {
						try {
							//是单例:则开始创建单例bean的实例
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
							// Explicitly remove instance from singleton cache: It might have been put there
							// eagerly by the creation process, to allow for circular reference resolution.
							// Also remove any beans that received a temporary reference to the bean.
							destroySingleton(beanName);
							throw ex;
						}
					});
					// 获取bean实例对象
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}

				// 如果是原型bean
				else if (mbd.isPrototype()) {
					// It's a prototype -> create a new instance.
					Object prototypeInstance = null;
					try {
						// 实例化前置准备工作
						beforePrototypeCreation(beanName);
						// 开始实例化
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						// 实例化以后的处理工作
						afterPrototypeCreation(beanName);
					}
					// 获取原型bean实例对象
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}

				// 其他bean类型处理
				else {
					String scopeName = mbd.getScope();
					final Scope scope = this.scopes.get(scopeName);
					// 空抛出异常
					if (scope == null) {
						throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
					}
					try {
						// 处理流程类似原型
						Object scopedInstance = scope.get(beanName, () -> {
							// 创建其他类型作用域bean的前置准备工作
							beforePrototypeCreation(beanName);
							try {
								// 创建其他类型作用域bean
								return createBean(beanName, mbd, args);
							}
							finally {
								// 后置处理作用
								afterPrototypeCreation(beanName);
							}
						});
						// 获取其他作用域类型实例化对象
						bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
					}
					catch (IllegalStateException ex) {
						throw new BeanCreationException(beanName,
								"Scope '" + scopeName + "' is not active for the current thread; consider " +
								"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
								ex);
					}
				}
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName);
				throw ex;
			}
		}

		// Check if required type matches the type of the actual bean instance.
		// 如果requiredType,且bean类型与入参要求不一致,则需要惊喜转换
		if (requiredType != null && !requiredType.isInstance(bean)) {
			try {
				// 将BeanDefinition转化成指定类型的bean
				T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
				if (convertedBean == null) {
					throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
				}
				return convertedBean;
			}
			catch (TypeMismatchException ex) {
				if (logger.isTraceEnabled()) {
					logger.trace("Failed to convert bean '" + name + "' to required type '" +
							ClassUtils.getQualifiedName(requiredType) + "'", ex);
				}
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
			}
		}
		return (T) bean;
	}

在Spring框架中,doGetBean方法是获取Bean实例的核心方法。这个方法涉及很多步骤,包括从缓存中获取单例Bean、处理原型Bean的创建、检查Bean定义、处理循环依赖等。下面我们会想分析refresh方法一样,先整体看下大概内容,再细节到一个一个方法进行解读。

流程总结

  1. 获取转换后的Bean名称:
    ○ 通过transformedBeanName方法获取转换后的Bean名称。
  2. 单例缓存检查:
    ○ 检查单例缓存中是否有手动注册的单例Bean。如果存在并且args为空,则直接从缓存中获取该Bean实例。
    ○ 如果在缓存中找到了Bean实例,并且args为空,则获取该Bean的实际对象并返回。
  3. Bean创建:
    ○ 如果单例缓存中没有找到该Bean实例,或者args不为空,则准备创建该Bean。
    ○ 如果当前Bean是Prototype且正在创建,则抛出异常,避免循环依赖。
    ○ 检查当前Bean的定义是否存在于当前工厂中,如果不存在则向父工厂请求该Bean实例。
  4. 标记Bean创建状态:
    ○ 如果typeCheckOnly为false,则将该Bean标记为已经开始创建。
  5. 合并Bean定义:
    ○ 合并容器中的Bean定义,得到新的Root类型的Bean定义。
  6. 校验合并后的Bean定义:
    ○ 校验合并后的Bean定义是否符合实例化要求,例如是否是抽象Bean。
  7. 处理依赖关系:
    ○ 获取当前Bean依赖的Bean数组,并递归调用getBean方法,提前实例化需要依赖的Bean。
  8. 实例化Bean:
    ○ 根据Bean的作用域(单例、原型或其他)进行实例化。
    ○ 对于单例Bean,获取单例缓存或创建新的单例实例。
    ○ 对于原型Bean,创建新的原型实例。
    ○ 对于其他作用域的Bean,通过作用域获取Bean实例。
  9. 类型转换:
    ○ 如果requiredType不为空且Bean实例的类型与requiredType不一致,则进行类型转换。

doGetBean方法是Spring框架中Bean创建与获取的核心逻辑,实现了复杂的Bean生命周期管理。通过单例缓存合并Bean定义、处理依赖关系以及类型转换等步骤,确保了Bean实例的正确创建与获取。此流程通过细致的检查与处理,避免了循环依赖,并支持多种作用域的Bean管理,为应用提供了灵活且可靠的Bean管理机制。

总结

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1903126.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

动态白色小幽灵404网站源码

动态白色小幽灵404网站源码&#xff0c;页面时单页HTML源码&#xff0c;将代码放到空白的html里面&#xff0c;鼠标双击html即可查看效果&#xff0c;或者上传到服务器&#xff0c;错误页重定向这个界面即可&#xff0c;喜欢的朋友可以拿去使用 <!DOCTYPE html> <ht…

联想小新14Pro,误删了一个注册表,怎么办?

&#x1f3c6;本文收录于「Bug调优」专栏&#xff0c;主要记录项目实战过程中的Bug之前因后果及提供真实有效的解决方案&#xff0c;希望能够助你一臂之力&#xff0c;帮你早日登顶实现财富自由&#x1f680;&#xff1b;同时&#xff0c;欢迎大家关注&&收藏&&…

uniapp报错--app.json: 在项目根目录未找到 app.json

【问题】 刚创建好的uni-app项目&#xff0c;运行微信小程序控制台报错如下&#xff1a; 【解决方案】 1. 程序根目录打开project.config.json文件 2. 配置miniprogramRoot&#xff0c;指定小程序代码的根目录 我的小程序代码编译后的工程文件目录为&#xff1a;dist/dev/mp…

Java常见面试题汇总带答案

本文分为十九个模块,分别是: Java 基础、容器、多线程、反射、对象拷贝、Java Web 、异常、网 络、设计模式、Spring/Spring MVC、Spring Boot/Spring Cloud、Hibernate、MyBatis、RabbitMQ、 Kafka、Zookeeper、MySQL、Redis、JVM 等等… JDK 和 JRE 有什么区别? JDK:Jav…

linux软链接和硬链接的区别

1 创建软链接和硬链接 如下图所示&#xff0c;一开始有两个文件soft和hard。使用 ln -s soft soft1创建软链接&#xff0c;soft1是soft的软链接&#xff1b;使用ln hard hard1创建硬链接&#xff0c;hard1是hard的硬链接。可以看到软链接的文件类型和其它3个文件的文件类型是不…

【测试专题】软件总体计划方案(2024原件word)

测试目标&#xff1a;确保项目的需求分析说明书中的所有功能需求都已实现&#xff0c;且能正常运行&#xff1b;确保项目的业务流程符合用户和产品设计要求&#xff1b;确保项目的界面美观、风格一致、易学习、易操作、易理解。 获取&#xff1a;软件全套文档过去进主页。 一、…

什么是五级流水?银行眼中的“好流水”,到底是什么样的?

无论是按揭买房还是日常贷款&#xff0c;银行流水都是绕不开的一环。规划好你的流水&#xff0c;不仅能让你在申请贷款时更有底气&#xff0c;还可能帮你省下不少冤枉钱。今天&#xff0c;咱们就来一场深度剖析&#xff0c;聊聊如何在按揭贷款、个人经营抵押贷款前&#xff0c;…

STM32-SPI和W25Q64

本内容基于江协科技STM32视频学习之后整理而得。 文章目录 1. SPI&#xff08;串行外设接口&#xff09;通信1.1 SPI通信简介1.2 硬件电路1.3 移位示意图1.4 SPI时序基本单元1.5 SPI时序1.5.1 发送指令1.5.2 指定地址写1.5.3 指定地址读 2. W25Q642.1 W25Q64简介2.2 硬件电路2…

计网_计算机网络概述

2024.07.03&#xff1a;计算机网络概述 第1节 计算机网络概述 1.1 互连网与互联网1.1.1总结1.1.2 因特网(互联网)发展[自行了解] 1.2 计算机网络组成1.2.1 计算机网络组成方式11.2.2 计算机网络组成方式21.2.3 计算机网络组成方式3 1.3 三种交换方式1.3.1 电路交换(1) 电路交换…

常见的Java运行时异常

常见的Java运行时异常 1、ArithmeticException&#xff08;算术异常&#xff09;2、ClassCastException &#xff08;类转换异常&#xff09;3、IllegalArgumentException &#xff08;非法参数异常&#xff09;4、IndexOutOfBoundsException &#xff08;下标越界异常&#xf…

C语言 | Leetcode C语言题解之第220题存在重复元素III

题目&#xff1a; 题解&#xff1a; struct HashTable {int key;int val;UT_hash_handle hh; };int getID(int x, long long w) {return x < 0 ? (x 1ll) / w - 1 : x / w; }struct HashTable* query(struct HashTable* hashTable, int x) {struct HashTable* tmp;HASH_F…

【Python】已解决:(Python xml库 import xml.dom.minidom导包报错)‘No module named dom’

文章目录 一、分析问题背景二、可能出错的原因三、错误代码示例四、正确代码示例五、注意事项 已解决&#xff1a;&#xff08;Python xml库 import xml.dom.minidom导包报错&#xff09;‘No module named dom’ 一、分析问题背景 在使用Python处理XML文件时&#xff0c;xml…

收银系统源码-线上商城预售功能

1.功能描述 预售&#xff1a;智慧新零售收银系统&#xff0c;线上商城营销插件之一&#xff0c;商品出售时可设置以支付定金或全款的方式提前预售&#xff0c;门店按订单量备货&#xff0c;降低压货成本&#xff1b; 2.适用场景 易损商品提前下单备货&#xff0c;如水果生鲜…

【MySQL】1.初识MySQL

初识MySQL 一.MySQL 安装1.卸载已有的 MySQL2.获取官方 yum 源3.安装 MySQL4.登录 MySQL5.配置 my.cnf 二.MySQL 数据库基础1.MySQL 是什么&#xff1f;2.服务器&#xff0c;数据库和表3.mysqld 的层状结构4.SQL 语句分类 一.MySQL 安装 1.卸载已有的 MySQL //查询是否有相关…

U盘非安全退出后的格式化危机与高效恢复策略

在数字化时代&#xff0c;U盘作为数据存储与传输的重要工具&#xff0c;其数据安全备受关注。然而&#xff0c;一个常见的操作失误——U盘没有安全退出便直接拔出&#xff0c;随后再插入时却遭遇“需要格式化”的提示&#xff0c;这不仅让用户措手不及&#xff0c;更可能意味着…

多方SQL计算场景下,如何达成双方共识,确认多方计算作业的安全性

安全多方计算在SQL场景下的限制 随着MPC、隐私计算等概念的流行&#xff0c; 诸多政府机构、金融企业开始考虑参与到多方计算的场景中&#xff0c; 扩展数据的应用价值。 以下面这个场景为例&#xff0c; 银行可能希望获取水电局和税务局的数据&#xff0c;来综合计算得到各…

huggingface笔记:gpt2

0 使用的tips GPT-2是一个具有绝对位置嵌入的模型&#xff0c;因此通常建议在输入的右侧而不是左侧填充GPT-2是通过因果语言建模&#xff08;CLM&#xff09;目标进行训练的&#xff0c;因此在预测序列中的下一个标记方面非常强大 利用这一特性&#xff0c;GPT-2可以生成语法连…

阿里云Elasticsearch-趣味体验

阿里云Elasticsearch-趣味体验 什么是阿里云Elasticsearch阿里云Elasticsearch开通服务查看Elasticsearch实例配置Kibana公网IP登录Elasticsearch添加测试数据 Kibana数据分析查看数据字段筛选数据页面条件筛选KQL语法筛选保存搜索语句导出筛选结果指定列表展示字段写在最后 什…

PyMuPDF 操作手册 - 10 API - Pixmap属性方法和简短说明

文章目录 https://pymupdf.readthedocs.io/en/latest/pixmap.html 方法/属性简短描述Pixmap.clear_with()清除像素图的部分Pixmap.color_count()确定使用的颜色Pixmap.color_topusage()确定最常用颜色的份额Pixmap.copy()复制另一个像素图的部分内容Pixmap.gamma_with()将 Gamm…

multisim中关于74ls192n和DSWPK开关仿真图分析(减法计数器)

&#x1f3c6;本文收录于「Bug调优」专栏&#xff0c;主要记录项目实战过程中的Bug之前因后果及提供真实有效的解决方案&#xff0c;希望能够助你一臂之力&#xff0c;帮你早日登顶实现财富自由&#x1f680;&#xff1b;同时&#xff0c;欢迎大家关注&&收藏&&…