Spring循环引用-@Async注解启动报错分析

目录

一、问题描述

二、问题分析

1、情景1

2、情景2

3、分析

三、解决方法

四、结论


一、问题描述

Spring的bean相互引用下,并且其中一个bean含有异步注解@Async,启动可能会出现错误:

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'bean1Service': Bean with name 'bean1Service' has been injected into other beans [bean2Service] 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.
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:638) ~[spring-beans-5.3.2.jar:5.3.2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.2.jar:5.3.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.2.jar:5.3.2]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.2.jar:5.3.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.2.jar:5.3.2]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.2.jar:5.3.2]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.2.jar:5.3.2]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:923) ~[spring-context-5.3.2.jar:5.3.2]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588) ~[spring-context-5.3.2.jar:5.3.2]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144) ~[spring-boot-2.4.1.jar:2.4.1]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767) [spring-boot-2.4.1.jar:2.4.1]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.4.1.jar:2.4.1]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426) [spring-boot-2.4.1.jar:2.4.1]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) [spring-boot-2.4.1.jar:2.4.1]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1309) [spring-boot-2.4.1.jar:2.4.1]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1298) [spring-boot-2.4.1.jar:2.4.1]
    at com.lb.reference.ReferenceApplication.main(ReferenceApplication.java:12) [classes/:na]

二、问题分析

环境 :jdk1.8.0_191 Springboot2.4.1

工具:eclipse 2021-09 (4.21.0)

项目:

Spring循环引用-@Async注解启动报错分析_第1张图片


	4.0.0

	lb
	cycle-reference
	0.0.1-SNAPSHOT
	jar

	cycle-reference
	http://maven.apache.org

	
		org.springframework.boot
		spring-boot-starter-parent
		2.4.1
		 
	

	
		UTF-8
	

	
		
			junit
			junit
			test
		
		
			org.springframework.boot
			spring-boot-starter-web
		
	

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync
@SpringBootApplication
public class ReferenceApplication {

	public static void main(String[] args) {
		SpringApplication.run(ReferenceApplication.class, args);
	}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class Bean1Service {

	@Autowired
	private Bean2Service bean2;
	
	@Async
	public void bean1() {
		bean2.bean2();
	}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Bean2Service {

	@Autowired
	private Bean1Service bean;
	
	public void bean2() {
		bean.bean1();
	}
}

1、情景1

com.lb.reference.service.Bean1Service有@Async

com.lb.reference.service.Bean2Service无@Async

启动报错

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'bean1Service': Bean with name 'bean1Service' has been injected into other beans [bean2Service] 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.
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:638) ~[spring-beans-5.3.2.jar:5.3.2]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.2.jar:5.3.2]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.2.jar:5.3.2]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.2.jar:5.3.2]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.2.jar:5.3.2]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.2.jar:5.3.2]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.2.jar:5.3.2]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:923) ~[spring-context-5.3.2.jar:5.3.2]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588) ~[spring-context-5.3.2.jar:5.3.2]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144) ~[spring-boot-2.4.1.jar:2.4.1]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767) [spring-boot-2.4.1.jar:2.4.1]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.4.1.jar:2.4.1]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426) [spring-boot-2.4.1.jar:2.4.1]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) [spring-boot-2.4.1.jar:2.4.1]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1309) [spring-boot-2.4.1.jar:2.4.1]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1298) [spring-boot-2.4.1.jar:2.4.1]
	at com.lb.reference.ReferenceApplication.main(ReferenceApplication.java:12) [classes/:na]

2、情景2

com.lb.reference.service.Bean1Service无@Async

com.lb.reference.service.Bean2Service有@Async

启动正常


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.1)

2021-12-17 21:52:47.449  INFO 8816 --- [           main] com.lb.reference.ReferenceApplication    : Starting ReferenceApplication using Java 1.8.0_191 on DESKTOP-58VVQ1F with PID 8816 (D:\java\ws_1\cycle-reference\target\classes started by liangbo in D:\java\ws_1\cycle-reference)
2021-12-17 21:52:47.453  INFO 8816 --- [           main] com.lb.reference.ReferenceApplication    : No active profile set, falling back to default profiles: default
2021-12-17 21:52:49.544  INFO 8816 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-12-17 21:52:49.560  INFO 8816 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-12-17 21:52:49.560  INFO 8816 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.41]
2021-12-17 21:52:49.665  INFO 8816 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-12-17 21:52:49.665  INFO 8816 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2148 ms
2021-12-17 21:52:50.167  INFO 8816 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2021-12-17 21:52:50.844  INFO 8816 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-12-17 21:52:50.861  INFO 8816 --- [           main] com.lb.reference.ReferenceApplication    : Started ReferenceApplication in 3.937 seconds (JVM running for 4.66)

3、分析

(1)、bean初始化顺序:bean1Service、bean2Service

位置:org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons()

Spring循环引用-@Async注解启动报错分析_第2张图片

(2)、spring默认提前暴露bean引用(allowCircularReferences=true),bean1工厂类加入三级缓存singletonFactories

位置:org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.addSingletonFactory(String, ObjectFactory)

Spring循环引用-@Async注解启动报错分析_第3张图片

(3)、 bean1属性填充

位置:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(String, RootBeanDefinition, Object[]) 

Spring循环引用-@Async注解启动报错分析_第4张图片

(4)、发现依赖bean2,从bean容器找,还没初始化,接着初始化bean2(getBean()获取bean,没有则初始化)

位置:org.springframework.beans.factory.support.AbstractBeanFactory.getBean(String)

Spring循环引用-@Async注解启动报错分析_第5张图片

(5)、bean2提前暴露引用,和bean1一致,加入工厂

Spring循环引用-@Async注解启动报错分析_第6张图片

(6)、bean2初始化完成后,填充到bean1属性,接着初始化bean1

Spring循环引用-@Async注解启动报错分析_第7张图片

 

(7)、bean1从二级缓存earlySingletonObjects获取提前暴露的bean1(刚才还是在三级缓存singletonFactories,为啥,现在在二级缓存earlySingletonObjects?这个是初始化bean2时,由于依赖bean1,在从bean容器获取bean1时,从三级缓存提升至二级缓存的,填充至bean2)

三级缓存提升至二级缓存

Spring循环引用-@Async注解启动报错分析_第8张图片

 从二级缓存获取bean1

Spring循环引用-@Async注解启动报错分析_第9张图片

 (8)、在initializeBean方法中生成异步代理对象(后置处理器org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor完成代理),原bean和代理对象是两个对象,前后bean版本不一致,故抛异常

Spring循环引用-@Async注解启动报错分析_第10张图片

三、解决方法

1、去除循环引用

2、含有@Async注解bean延迟生成,引用属性加@Lazy

Spring循环引用-@Async注解启动报错分析_第11张图片

2、修改属性org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.allowRawInjectionDespiteWrapping为true,跳过检查

四、结论

含有@Async注解先初始化,启动会报错

你可能感兴趣的:(spring,java,后端)