一看就懂,Spring IOC 三级缓存如何解决循环依赖

2024-05-29 06:08

本文主要是介绍一看就懂,Spring IOC 三级缓存如何解决循环依赖,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

历时一周的时间,前后经历4/5次更改,浓缩出本文~

目录

 Bean 创建时机

Spring 创建 bean 三步曲

循环依赖

关键代码


 Bean 创建时机

AbstractApplicationContext.javapublic void refresh() { finishBeanFactoryInitialization(beanFactory);  }protected finishBeanFactoryInitialization(beanFactory) {// Instantiate all remaining (non-lazy-init) singletons.beanFactory.preInstantiateSingletons}    

     

Spring 创建 bean 三步曲

1.  反射调用无参构造创建 bean:   Constructor.newInstance()

2.  为 bean 属性赋值: populateBean()

3.  初始化 bean:initializeBean()

循环依赖

关于循环依赖的问题已经在上图中说明,为了看的更清楚,整理如下流程图:

解释下上图, A依赖B, B依赖A, 

1. spring 获取 a,a 不存在缓存,开始创建

2. a 创建后放入三级缓存

3. 赋值 a 的属性,发现依赖了 b

4. 获取 b, b 不存在缓存,开始创建

5. b 创建后放入三级缓存

6. 赋值 b 的属性, 发现依赖了 a

7. 从三级缓存获取 a (的代理,如果需要的话), 并放入二级缓存(2中操作的)

8. 注入到 b 

9. 初始化 b (生成代理对象)

10. b 放入一级缓存(b 的创建全部完成)

11. 把 b 注入 a

12. 接着 3, 初始化 a,并没有生成代理!

13. 从二级缓存获取 a 的代理对象(7中操作的)

14. 将 a 的代理对象放入一级缓存(b 的创建全部完成)

关键代码

获取 bean

	protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)throws BeansException {String beanName = transformedBeanName(name);Object beanInstance;// 从缓存中获取,一级->二级->三级, b 初始化时获取 a,从三级缓存获取并移入二级Object sharedInstance = getSingleton(beanName);// 缓存中有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,或者 factoryBean.getObject()beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);}else {//缓存中没有,再次尝试从缓存获取,没有则调用 createBean 返回的最终 bean(如果用了aop,是增强的bean) 并放入一级缓存中。if (mbd.isSingleton()) {sharedInstance = getSingleton(beanName, () -> {try {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;}});beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);}else if (mbd.isPrototype()) {}else {}catch (IllegalStateException ex) {throw new ScopeNotActiveException(beanName, scopeName, ex);}}}catch (BeansException ex) {beanCreation.tag("exception", ex.getClass().toString());beanCreation.tag("message", String.valueOf(ex.getMessage()));cleanupAfterBeanCreationFailure(beanName);throw ex;}finally {beanCreation.end();}}return adaptBeanInstance(name, beanInstance, requiredType);}
AbstractBeanFactory.java

创建 bean 并初始化过程:

	protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)throws BeanCreationException {// Instantiate the bean.BeanWrapper instanceWrapper = null;if (mbd.isSingleton()) {instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);}if (instanceWrapper == null) {// 1. 反射创建 beaninstanceWrapper = createBeanInstance(beanName, mbd, args);}Object bean = instanceWrapper.getWrappedInstance();// Eagerly cache singletons to be able to resolve circular references// even when triggered by lifecycle interfaces like BeanFactoryAware.boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&isSingletonCurrentlyInCreation(beanName));if (earlySingletonExposure) {if (logger.isTraceEnabled()) {logger.trace("Eagerly caching bean '" + beanName +"' to allow for resolving potential circular references");}// 2. a、b 创建后都会被放入三级缓存:beanName-> singletonFactory// b 初始化时,会从三级缓存的 singletonFactory.getObject() 拿到 a 的代理对象addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));}// 3. 初始化(resolveDependency, 生成代理对象)Object exposedObject = bean;try {populateBean(beanName, mbd, instanceWrapper);// b 在这里会生成代理对象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) {Object earlySingletonReference = getSingleton(beanName, false);if (earlySingletonReference != null) {if (exposedObject == bean) {exposedObject = earlySingletonReference;}else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {String[] dependentBeans = getDependentBeans(beanName);Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);for (String dependentBean : dependentBeans) {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 " +"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");}}}}// Register bean as disposable.try {registerDisposableBeanIfNecessary(beanName, bean, mbd);}catch (BeanDefinitionValidationException ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);}return exposedObject;}
AbstractAutowireCapableBeanFactory.java

7 中获取 a 时会从三级缓存中获取,singletonFactory.getObject 时会生成代理:

	protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {Object exposedObject = bean;if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {// 重要!!如果使用了aop, InfrastructureAdvisorAutoProxyCreator 会返回代理对象exposedObject = bp.getEarlyBeanReference(exposedObject, beanName);}}return exposedObject;}

AbstractAutowireCapableBeanFactory.java

总结

1. 一级缓存 存放已经 ready 的 bean,供其他 bean 使用

private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

2. 二级缓存,存放循环依赖中首先被创建的 bean(被增强后的单例 bean)

private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);

3. 三级缓存, 存放对象名和对象工厂

Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

二级缓存的意义就在于:如果使用了 aop , 缓存了被增强对象,而不是通过三级缓存每次都创建个增强对象。


如果觉得还不错的话,关注、分享、在看(关注不失联~), 原创不易,且看且珍惜~

这篇关于一看就懂,Spring IOC 三级缓存如何解决循环依赖的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1012856

相关文章

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件