【Spring源码】小白速通解析Spring源码,从0到1,持续更新!

Spring源码

参考资料

https://www.bilibili.com/video/BV1Tz4y1a7FM

https://www.bilibili.com/video/BV1iz4y1b75q

image-20230727230632443

bean工厂

DefaultListableBeanFactory(最原始)

bean的生命周期

创建(实例化)–>依赖注入–>-初始化–>销毁

bean–>推断构造方法(默认是无参构造,或指定的构造方法)–>实例化成普通对象(相当于new bean)

–>进行依赖注入(bean里的属性)–>执行afterPropertiesSet()(InitializingBean的一个回调方法,同@PostConstruct)

–>初始化后是否需要AOP–>AOP–>代理对象(target=普通对象)–>把对象放入Map<beanname,bean对象>单例池

image-20230817225424846

//真正创建Bean的方法protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)throws BeanCreationException {// Instantiate the bean.//封装被创建的Bean对象BeanWrapper instanceWrapper = null;if (mbd.isSingleton()) {instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);}if (instanceWrapper == null) {instanceWrapper = createBeanInstance(beanName, mbd, args);}final Object bean = instanceWrapper.getWrappedInstance();//获取实例化对象的类型Class<?> beanType = instanceWrapper.getWrappedClass();if (beanType != NullBean.class) {mbd.resolvedTargetType = beanType;}// Allow post-processors to modify the merged bean definition.//调用PostProcessor后置处理器synchronized (mbd.postProcessingLock) {if (!mbd.postProcessed) {try {applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);}catch (Throwable ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"Post-processing of merged bean definition failed", ex);}mbd.postProcessed = true;}}// Eagerly cache singletons to be able to resolve circular references// even when triggered by lifecycle interfaces like BeanFactoryAware.//向容器中缓存单例模式的Bean对象,以防循环引用boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&isSingletonCurrentlyInCreation(beanName));if (earlySingletonExposure) {if (logger.isDebugEnabled()) {logger.debug("Eagerly caching bean '" + beanName +"' to allow for resolving potential circular references");}//这里是一个匿名内部类,为了防止循环引用,尽早持有对象的引用addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));}// Initialize the bean instance.//Bean对象的初始化,依赖注入在此触发//这个exposedObject在初始化完成之后返回作为依赖注入完成后的BeanObject exposedObject = bean;try {//将Bean实例对象封装,并且Bean定义中配置的属性值赋值给实例对象populateBean(beanName, mbd, instanceWrapper);//初始化Bean对象exposedObject = initializeBean(beanName, exposedObject, mbd);}catch (Throwable ex) {if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {throw (BeanCreationException) ex;}else {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);}}if (earlySingletonExposure) {//获取指定名称的已注册的单例模式Bean对象Object earlySingletonReference = getSingleton(beanName, false);if (earlySingletonReference != null) {//根据名称获取的已注册的Bean和正在实例化的Bean是同一个if (exposedObject == bean) {//当前实例化的Bean初始化完成exposedObject = earlySingletonReference;}//当前Bean依赖其他Bean,并且当发生循环引用时不允许新创建实例对象else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {String[] dependentBeans = getDependentBeans(beanName);Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);//获取当前Bean所依赖的其他Beanfor (String dependentBean : dependentBeans) {//对依赖Bean进行类型检查if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {actualDependentBeans.add(dependentBean);}}if (!actualDependentBeans.isEmpty()) {throw new BeanCurrentlyInCreationException(beanName,"Bean with name '" + beanName + "' has been injected into other beans [" +StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +"] in its raw version as part of a circular reference, but has eventually been " +"wrapped. This means that said other beans do not use the final version of the " +"bean. This is often the result of over-eager type matching - consider using " +"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");}}}}// Register bean as disposable.//注册完成依赖注入的Beantry {registerDisposableBeanIfNecessary(beanName, bean, mbd);}catch (BeanDefinitionValidationException ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);}return exposedObject;}
//初始容器创建的Bean实例对象,为其添加BeanPostProcessor后置处理器protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {//JDK的安全机制验证权限if (System.getSecurityManager() != null) {//实现PrivilegedAction接口的匿名内部类AccessController.doPrivileged((PrivilegedAction<Object>) () -> {invokeAwareMethods(beanName, bean);return null;}, getAccessControlContext());}else {//为Bean实例对象包装相关属性,如名称,类加载器,所属容器等信息invokeAwareMethods(beanName, bean);}Object wrappedBean = bean;//对BeanPostProcessor后置处理器的postProcessBeforeInitialization//回调方法的调用,为Bean实例初始化前做一些处理if (mbd == null || !mbd.isSynthetic()) {wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);}//调用Bean实例对象初始化的方法,这个初始化方法是在Spring Bean定义配置//文件中通过init-method属性指定的try {invokeInitMethods(beanName, wrappedBean, mbd);}catch (Throwable ex) {throw new BeanCreationException((mbd != null ? mbd.getResourceDescription() : null),beanName, "Invocation of init method failed", ex);}//对BeanPostProcessor后置处理器的postProcessAfterInitialization//回调方法的调用,为Bean实例初始化之后做一些处理if (mbd == null || !mbd.isSynthetic()) {wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);}return wrappedBean;}

三级缓存解决循环依赖

循环依赖

在A创建的过程中,A的属性B需要注入属性A

  • singletonObjects(一级缓存)
  • earlysingletonObjects(二级缓存)
  • singletonFactories(三级缓存)
  • private final Map<String, Object> singletonObjects = new ConcurrentHashMap(256);
    private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap(16);
    private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap(16);
  1. 创建的A放入 Set singletonsCurrentlyInCreation(只要创建就放入set,表示bean正在初始化)
  2. 首先是实例化,new 普通对象,addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));为了防止循环引用,尽早持有对象的引用,第二个参数是一个lamda表达式可用来获取普通对象
  3. 在A填充B时,B需要注入A,判断A正在初始化,此时出现循环依赖
  4. 先向二级缓存里查找,在多方循环中保证创建的是都是同一个代理对象A
  5. 再向三级缓存里查找,没有则执行lamda获取普通对象,并且进行AOP,生成代理对象
  6. 放入bean到二级缓存中
  7. 填充其他的属性
  8. 进行Aop的逻辑,若是循环依赖则会提前进行Aop(step5)而不是现在
  9. 在二级缓存里查找,是不是已经有已经生成好的bean
  10. 添加到单例池
  11. Set中removeA,标识初始化完成

beanFactory

image-20230816230618815

四个Applicationcontext

FileSystemXmlApplicationContext

ClassPathXmlApplicationContext

AnnotationConfigApplicationContext

AnnotationConfigWebApplicationContext

GenericApplicationContext(是一个干净的容器)

后置处理器(PostProcessor)

CommonAnnotationBeanPostProcessor

Ordered.LOWEST_PRECEDENCE - 3

@Resource @PostConstruct @PreDestroy

解析WebService关于JAX-WS的相关注解,EJB相关的注解

AutowiredAnnotationBeanPostProcessor

Ordered.LOWEST_PRECEDENCE - 2

处理@Autowire注解,@Value注解,处理javax.inject.Inject JSR-330注解

	//处理类中的属性@Overridepublic PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {//获取指定类中autowire相关注解的元信息InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);try {//对Bean的属性进行自动注入metadata.inject(bean, beanName, pvs);}catch (BeanCreationException ex) {throw ex;}catch (Throwable ex) {throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);}return pvs;}

image-20230818000115153

BeanPostProcessor

处理器定义了Bean 初始化 前后执行的方法。

public interface BeanPostProcessor {//自定义初始化方法之前执行@Nullabledefault Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {return bean;}//自定义初始化方法之后执行@Nullabledefault Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {return bean;}}

InstantiationAwareBeanPostProcessor

该处理器定义了Bean 实例化 前后执行的方法。

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {//实例化之前@Nullabledefault Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException { //这里可以自定义代理类return null;}//实例化后-但是执行在初始化之前default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {return true;}//处理bean的Properties值@Nullabledefault PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)throws BeansException {return null;}}

image-20230817234200283

DestructionAwareBeanPostProcessor

该处理器了销毁Bean之前的操作。

public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {//bean销毁之前void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException;//bean是否需要销毁default boolean requiresDestruction(Object bean) {return true;}}

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

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

相关文章

数据生成 | MATLAB实现WGAN生成对抗网络数据生成

数据生成 | MATLAB实现WGAN生成对抗网络数据生成 目录 数据生成 | MATLAB实现WGAN生成对抗网络数据生成生成效果基本描述程序设计参考资料 生成效果 基本描述 1.WGAN生成对抗网络&#xff0c;数据生成&#xff0c;样本生成程序&#xff0c;MATLAB程序&#xff1b; 2.适用于MATL…

【游戏评测】河洛群侠传一周目玩后感

总游戏时长接近100小时&#xff0c;刚好一个月。 这两天费了点劲做了些成就&#xff0c;刷了等级&#xff0c;把最终决战做了。 总体感觉还是不错的。游戏是开放世界3D游戏&#xff0c;Unity引擎&#xff0c;瑕疵很多&#xff0c;但胜在剧情扎实&#xff0c;天赋系统、秘籍功法…

JDBC Vertica Source Connector 使用文档

支持以下引擎 Spark Flink SeaTunnel Zeta 关键特性 批处理 精确一次性处理 列投影 并行处理 支持用户自定义拆分 支持查询 SQL 并实现投影效果 描述 通过 JDBC 读取外部数据源数据。 支持的数据源信息 DatasourceSupported versionsDriverUrlMavenVerticaDifferent depen…

设计HTML5表格

在网页设计中&#xff0c;表格主要用于显示包含行、列结构的二维数据&#xff0c;如财务表格、调查数据、日历表、时刻表、节目表等。在大多数情况下&#xff0c;这类信息都由列标题或行标题及数据构成。本章将详细介绍表格在网页设计中的应用&#xff0c;包括设计符合标准化的…

【第七讲---视觉里程计1】

视觉里程计就是通过对图像进行特征提取与匹配得到两帧之间的位姿&#xff0c;并进行估计相机运动。 经典SLAM中以相机位姿-路标来描述SLAM过程 特征提取与匹配 路标是三维空间中固定不变的点&#xff0c;可以在特定位姿下观测到在视觉SLAM中&#xff0c;可利用图像特征点作为…

2023 CCF BDCI 数字安全公开赛正式开启报名

2023 CCF BDCI 数字安全公开赛重磅来袭&#xff01; 全新的赛道场景 丰厚的赛事奖励 精彩的周边活动 数字安全守护人的狂欢盛宴 快来报名参加吧 大赛背景 伴随着数智化的持续加深&#xff0c;网络安全、数据安全风险遍布于所有场景之中&#xff0c;包括工业生产、能源、交…

2019年9月全国计算机等级考试真题(C语言二级)

2019年9月全国计算机等级考试真题&#xff08;C语言二级&#xff09; 第1题 1、“商品”与“顾客”两个实体集之间的联系一般是 A. 一对一 B. 一对多 C. 多对一 D. 多对多 正确答案&#xff1a;D 第2题 定义学生选修课程的关系模式&#xff1a;SC&#xff08;S#&#xff0c…

运营商三要素 API:构建安全高效的身份验证系统

当今数字化的世界中&#xff0c;身份验证是各行各业中至关重要的一环。为了保护用户的隐私和数据安全&#xff0c;企业需要寻求一种既安全可靠又高效便捷的身份验证方式。运营商三要素 API 应运而生&#xff0c;为构建安全高效的身份验证系统提供了有力的解决方案。 运营商三要…

R语言 列表中嵌套列名一致的多个数据框如何整合为一个数据框

在批量建模后容易得到list&#xff0c;list中的每个元素都是单个的tibble 或者 dataframe&#xff0c;如何将这些数据整合为一张表呢&#xff1f; 载入R包 library(broom) library(tidyverse) 模拟数据 models <- txhousing %>% group_by(city) %>% do(modlm(lo…

-Webkit-Box 在 Safari 中出现的兼容性问题

一、问题背景&#xff1a; UI要求要实现这样的效果&#xff0c;使用 display:-webket-box在chrome浏览器下完美解决 但是马上啪啪打脸&#xff0c;在safari浏览器下显示空白 &#xff0c;不能不说浏览器之间的兼容性简直就是天坑 二、解决办法 通过浏览器调试发现原本float的…

使用Pillow对图像进行变换

使用Pillow对图像进行变换 from PIL import Image, ImageEnhance# 原图 image Image.open("1.jpg") image.show()# 镜像 mirrored_image image.transpose(Image.FLIP_LEFT_RIGHT) mirrored_image.show() mirrored_image.save(mirror_image.jpg)# 旋转 rotated_imag…

VK36W1D浴缸,洁具高灵敏度电容式单点液体水位检测触摸芯片资料介绍

产品品牌&#xff1a;永嘉微电/VINKA 产品型号&#xff1a;VK36W1D 封装形式&#xff1a;SOT23-6L 产品年份&#xff1a;新年份 &#xff08;C21-163&#xff09; 产品特点&#xff1a;VK36W1D具有1个触摸检测通道&#xff0c;可用来检测水从无到有和水从有到无的动作。该…

一个模型解决所有类别的异常检测

文章目录 一、内容说明二、相关链接三、概述四、摘要1、现有方法存在的问题2、方案3、效果 五、作者的实验六、如何训练自己的数据1、数据准备2、修改配置文件3、代码优化修改4、模型训练与测试 七、结束 一、内容说明 在我接触的缺陷检测项目中&#xff0c;检测缺陷有两种方法…

网络通信基础

1.网络结构模式&#xff08;C/S和B/S&#xff09; (1)C/S结构模式 服务器 - 客户机&#xff0c;即 Client - Server&#xff08;C/S&#xff09;结构。 优点&#xff1a; 能充分发挥客户端 PC 的处理能力&#xff0c;很多工作可以在客户端处理后再提交给服务器&#xff…

大数据-玩转数据-Flink RedisSink

一、添加Redis Connector依赖 具体版本根据实际情况确定 <dependency><groupId>org.apache.flink</groupId><artifactId>flink-connector-redis_2.11</artifactId><version>1.1.5</version> </dependency>二、启动redis 参…

分类预测 | MATLAB实现DBN-SVM深度置信网络结合支持向量机多输入分类预测

分类预测 | MATLAB实现DBN-SVM深度置信网络结合支持向量机多输入分类预测 目录 分类预测 | MATLAB实现DBN-SVM深度置信网络结合支持向量机多输入分类预测预测效果基本介绍程序设计参考资料 预测效果 基本介绍 1.分类预测 | MATLAB实现DBN-SVM深度置信网络结合支持向量机多输入分…

回归预测 | MATLAB实现基于SAE堆叠自编辑器多输入单输出回归预测

回归预测 | MATLAB实现基于SAE堆叠自编辑器多输入单输出回归预测 目录 回归预测 | MATLAB实现基于SAE堆叠自编辑器多输入单输出回归预测预测效果基本介绍模型描述程序设计参考资料 预测效果 基本介绍 1.MATLAB实现基于SAE堆叠自编辑器多输入单输出回归预测&#xff1b; 2.运行环…

Request+Response

文章目录 1. 介绍2. Request对象2.1 Request继承体系2.2 Request获取请求数据1.获取请求行2.获取请求头3.获取请求体4. 请求参数的通用方式5. 解决中文乱码问题 2.3 Request请求转发请求转发资源间共享数据: 3. Response对象3.0 Response 继承体系3.1 Response设置响应数据的功…

iOS手机无法安装Charles 的ssl证书

问题描述 iOS客户端安装证书时一直卡在下载这一步&#xff0c;无法抓包 1、打开Charles&#xff0c;选择help→SSL Proxying→Install Charles Root Certificate on a Mobile Device or Remote Browser 2、按照步骤1中的提示进行操作&#xff0c;手机连接电脑代理&#xff0c;…

Spring系列七:声明式事务

&#x1f418;声明式事务 和AOP有密切的联系, 是AOP的一个实际的应用. &#x1f432;事务分类简述 ●分类 1.编程式事务: 示意代码, 传统方式 Connection connection JdbcUtils.getConnection(); try { //1.先设置事务不要自动提交 connection.setAutoCommit(false…