【实践向】当移除了三级缓存……

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

本文会手把手带你一起把使用二级缓存替换三级缓存看下移除了三级缓存只有二级缓存会出什么问题用实践回答那个被问了无数次的“为什么要有三级缓存”以及“二级缓存解决不了循环依赖问题吗”等类似问题( ̄∇ ̄)

既然要用二级缓存替换三级缓存我们大致回忆下(b_d)都在哪里用到了三级缓存

自问自答主要是两个地方

  1. 获取Bean的时候Spring在获取Bean的时候会先从一级缓存中找找不到会去二级缓存中找再找不到会到三级缓存

  1. 创建完Bean的实例对象后会将当前bean以及它的工厂对象添加进三级缓存

那我们分别将这两个地方中涉及到三级缓存的逻辑修改下

移除三级缓存

移除向三级缓存中查找Bean的逻辑

先来到Spring中使用三级缓存的位置就是DefaultSingletonBeanRegistry类中不知道如何找的客官可以参考

【Spring源码】2.试个水先~Debug找到传说中的三级缓存

DefaultSingletonBeanRegistry类中有个getSingleton()的方法里面是从缓存中获取Bean的逻辑

我们把这个函数整个复制下把原来的注释掉在复制的函数中进行修改

注意尽量不要直接在原函数上进行修改因为后面我们还要再改回来呢(˶‾᷄ ⁻̫ ‾᷅˵)

改成这样

@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {Object singletonObject = this.singletonObjects.get(beanName);
   if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {synchronized (this.singletonObjects) {singletonObject = this.earlySingletonObjects.get(beanName);
         return singletonObject;
      }   }return singletonObject != null ? singletonObject : null;
}

移除向三级缓存中添加Bean的逻辑

了解Bean的创建流程的客官还记不记得有个叫做addSingletonFactory()的方法可以参考文章【Spring源码】16. Bean的创建过程2

这个方法就在DefaultSingletonBeanRegistry类中

当前bean以及它的工厂对象就是在这个方法中被放入三级缓存的

我们想要移除三级缓存只保留二级缓存就需要把这个方法中对于三级缓存的操作修改为只保留二级缓存的操作

单击方法回到它位于doCreateBean()方法中的调用位置

addSingletonFactory()方法中操作了三个集合singletonFactories三级缓存、earlySingletonObjects二级缓存、registeredSingletons注册bean集合

去除三级缓存我们只添加对earlySingletonObjects二级缓存、registeredSingletons注册bean集合这两个集合的操作

由于这两个集合是类DefaultSingletonBeanRegistry私有的private因此想要在别的类中调用需要修改成公共的public

执行测试

修改完毕我们执行下上篇文章中的测试代码看是否会报错想要自己亲自执行下的可以直接去为文章

【保姆级】手把手Debug循环依赖的整体流程 中复制下

嘿嘿没问题对不对所以其实单纯的循环依赖二级缓存就足够了那么为什么非要再搞一个三级缓存呢

又自问自答因为代理

引入代理

新建测试类

代理类

我们再新建一个日志类AOP必然产生动态代理

package com.aqin.custom.circulate;

/** * @Description* @Authoraqin1012 AQin. * @Date11/23/22 1:19 PM * @Version1.0 */
public class MyLogger {public void beforeMethod() {System.out.println("beforeMethod");
   }public void afterMethod() {System.out.println("afterMethod");
   }}

配置类

在原有配置基础上添加日志类以及AOP相关配置

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"><bean id="beanA" class="com.aqin.custom.circulate.BeanA"><property name="beanB" ref="beanB"></property></bean><bean id="beanB" class="com.aqin.custom.circulate.BeanB"><property name="beanA" ref="beanA"></property></bean><bean id="myLogger" class="com.aqin.custom.circulate.MyLogger"></bean><aop:config><aop:aspect id="myLogger" ref="myLogger"><aop:pointcut id="method" expression="execution(* com.aqin.custom.circulate.*.*(..))"/><aop:before method="beforeMethod" pointcut-ref="method"/><aop:after method="afterMethod" pointcut-ref="method"/></aop:aspect></aop:config></beans>

添加依赖

在module下的build.gradle文件中添加AOP的依赖

不然会报下面👇的异常

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)#3a883ce7' of type [org.springframework.aop.aspectj.AspectJMethodBeforeAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3a883ce7': Resolution of declared constructors on bean Class [org.springframework.aop.aspectj.AspectJMethodBeforeAdvice] from ClassLoader [sun.misc.Launcher$AppClassLoader@73d16e93] failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/lang/JoinPoint

启动类

public class Test {public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("circulate.xml");
      BeanA beanA = applicationContext.getBean(BeanA.class);
      System.out.println(beanA);
      System.out.println(beanA.getBeanB());
   }}

启动类添加一行方法的调用用于测试AOP的执行效果

启动执行

果然、报错了=[,,_,,]:3

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'beanA': Bean with name 'beanA' has been injected into other beans [beanB] 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.

点击上图中黄色框框框住的类会定位到报错位置

所以是在执行doCreateBean()方法时报了这个异常

我们大致翻一下分析在最后一部分

在上下文初始化过程中遇到的异常 - 取消刷新尝试org.springframework.beans.factory.BeanCurrentlyInCreationException。创建名称为'beanA'的Bean时出错。名字为'beanA'的Bean已经作为循环引用的一部分被注入到其他Bean[beanB]的原始版本中但最终被包装了。这意味着上述其他Bean没有使用Bean的最终版本。这通常是过于急切的类型匹配的结果--例如考虑使用'getBeanNamesForType'并关闭'allowEagerInit'标志。

将代码改回去

执行成功(。・ω・。)ノ

分析与总结

上面的实践过程直观的证明了一个我们早就知道的结论(˶‾᷄ ⁻̫ ‾᷅˵)

如果不存在代理对象二级缓存就可以解决循环依赖性的问题但是当存在代理对象的时候二级缓存则无法完全解决循环依赖需要引入三级缓存

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6