多个bean之间相互依赖,形成了一个闭环。 比如:A依赖于B、B依赖于C、C依赖于A
通常来说,如果问Spring容器内部如何解决循环依赖问题,一定是指默认的单例Bean中,属性相互引用的场景。也就是说,Spring的循环依赖,是Spring容器注入时出现的问题。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>comgroupId>
<artifactId>spring-circular-dependencyartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>5.2.1.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>5.2.1.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.2.1.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjrtartifactId>
<version>1.8.9version>
dependency>
<dependency>
<groupId>org.apache.geronimo.bundlesgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.6.8_2version>
dependency>
dependencies>
project>
Bean01.java
package com.spring.bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author honey
* @date 2023-08-23 17:50:53
*/
@Component
public class Bean01 {
@Autowired
private Bean02 bean02;
}
Bean02.java
package com.spring.bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author honey
* @date 2023-08-23 17:52:55
*/
@Component
public class Bean02 {
@Autowired
private Bean01 bean01;
}
SpringConfig01.java
package com.spring.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @author honey
* @date 2023-08-23 17:59:37
*/
@Configuration
@ComponentScan(value = {"com.spring.bean"})
public class SpringConfig01 {
}
SpringTest01.java
package com.spring.test;
import com.spring.bean.Bean01;
import com.spring.bean.Bean02;
import com.spring.config.SpringConfig01;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author honey
* @date 2023-08-23 18:00:24
*/
public class SpringTest01 {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig01.class);
Bean01 bean01 = applicationContext.getBean("bean01", Bean01.class);
Bean02 bean02 = applicationContext.getBean("bean02", Bean02.class);
System.out.println(bean01);
System.out.println(bean02);
}
}
Spring默认情况下已经解决了循环依赖问题(单例Bean)
在SpringConfig01类上加上@EnableAsync注解
在Bean01类中使用@Async注解修饰的异步方法
Bean01.java
package com.spring.bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @author honey
* @date 2023-08-23 17:50:53
*/
@Component
public class Bean01 {
@Autowired
private Bean02 bean02;
@Async
public void test() {
System.out.println(Thread.currentThread().getName() + "Bean01测试中...");
}
}
运行结果
"C:\Program Files\Java\jdk1.8.0_191\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2021.1.1\lib\idea_rt.jar=57456:C:\Program Files\JetBrains\IntelliJ IDEA 2021.1.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_191\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\rt.jar;E:\知识点资料(第四年)\Spring源码解读\代码\spring-circular-dependency\target\classes;D:\maven_jar\org\springframework\spring-core\5.2.1.RELEASE\spring-core-5.2.1.RELEASE.jar;D:\maven_jar\org\springframework\spring-jcl\5.2.1.RELEASE\spring-jcl-5.2.1.RELEASE.jar;D:\maven_jar\org\springframework\spring-beans\5.2.1.RELEASE\spring-beans-5.2.1.RELEASE.jar;D:\maven_jar\org\springframework\spring-context\5.2.1.RELEASE\spring-context-5.2.1.RELEASE.jar;D:\maven_jar\org\springframework\spring-aop\5.2.1.RELEASE\spring-aop-5.2.1.RELEASE.jar;D:\maven_jar\org\springframework\spring-expression\5.2.1.RELEASE\spring-expression-5.2.1.RELEASE.jar;D:\maven_jar\org\aspectj\aspectjrt\1.8.9\aspectjrt-1.8.9.jar;D:\maven_jar\org\apache\geronimo\bundles\aspectjweaver\1.6.8_2\aspectjweaver-1.6.8_2.jar" com.spring.test.SpringTest01
八月 23, 2023 7:07:05 下午 org.springframework.context.support.AbstractApplicationContext refresh
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'bean01': Bean with name 'bean01' has been injected into other beans [bean02] 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.
Exception in thread "main" org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'bean01': Bean with name 'bean01' has been injected into other beans [bean02] 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.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:624)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:89)
at com.spring.test.SpringTest01.main(SpringTest01.java:15)
Process finished with exit code 1
Spring在扫描bean发现某个类方法被@Async修饰时,会通过后置处理器AsyncAnnotationBeanPostProcessor生成代理对象,而该后置处理器的顺序比处理AOP的后置处理器还靠后,因此会导致Spring处理不了循环依赖。
在Bean01类中循环依赖的属性上使用@Lazy注解
运行结果
AspectAop.java
package com.spring.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* @author honey
* @date 2023-08-23 18:26:33
*/
@Component
@Aspect
public class AspectAop {
@Pointcut("execution (* com.spring.bean.*.*(..))")
public void pointcut() {
}
@Around(value = "pointcut()")
public Object doAround(ProceedingJoinPoint point) throws Throwable {
System.out.println("doAround advice start");
Object result = point.proceed();
System.out.println("doAround advice end");
return result;
}
}
需要在Bean01和Bean02中加上一个普通方法,如:
package com.spring.bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author honey
* @date 2023-08-23 17:52:55
*/
@Component
public class Bean02 {
@Autowired
private Bean01 bean01;
public void add() {
}
}
SpringConfig01.java
package com.spring.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* @author honey
* @date 2023-08-23 17:59:37
*/
@Configuration
@ComponentScan(value = {"com.spring.bean", "com.spring.aop"})
@EnableAspectJAutoProxy
public class SpringConfig01 {
}
Spring底层通过三级缓存解决了循环依赖问题。
一级缓存:singletonObjects,也叫作单例池,存放已经经历了完整生命周期的Bean对象;
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
二级缓存:earlySingletonObjects,存放早期暴露出来的Bean对象,Bean的生命周期未结束(属性还未填充完整);
/** Cache of early singleton objects: bean name to bean instance. */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
三级缓存:singletonFactories,存放可以生成Bean的工厂;
/** Cache of singleton factories: bean name to ObjectFactory. */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
假设有两个对象分别是A和B,其中A依赖于B,B依赖于A
在创建A对象时,A对象完成实例化后,会将A对象封装成ObjectFactory存入三级缓存。
AbstractBeanFactory.java
AbstractAutowireCapableBeanFactory.java
ObjectFactory.java
如果该对象是单例对象且开启了循环依赖且该对象正在创建中,则会将该对象封装成ObjectFactory对象存入三级缓存。其中ObjectFactory是一个函数接口,在调用getObject()方法时,才会真正去执行lambda语句调用getEarlyBeanReference()方法。
// 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");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
DefaultSingletonBeanRegistry.java
在为A对象设置属性时,发现A对象依赖于B对象,则会去尝试获取B对象,由于此时B对象还未被创建,所以B对象也会走和A对象一样的创建逻辑,不同的是在为B对象设置属性时,发现B对象依赖于A对象,可以从三级缓存中获取得到A对象。
AbstractBeanFactory.java
DefaultSingletonBeanRegistry.java
此时存入二级缓存的是不完整对象,调用singletonFactory.getObject()方法实际上是在调用getEarlyBeanReference(beanName, mbd, bean)方法。
如果是正常情况下,返回原始对象
InstantiationAwareBeanPostProcessorAdapter.java
如果是开启了Aop的情况下,返回Aop代理对象
AbstractAutoProxyCreator.java
将获取到的A对象设置为B对象的属性并执行完B对象的完整生命周期后,将B对象存入一级缓存中并从二级缓存、三级缓存中移除。此处也使用了ObjectFactory这个函数接口。
AbstractBeanFactory.java
DefaultSingletonBeanRegistry.java
获取得到B对象后,接着执行A对象的生命周期,执行完成后和B对象一样存入一级缓存中。