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)

项目:

<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.0</modelVersion>

	<groupId>lb</groupId>
	<artifactId>cycle-reference</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>cycle-reference</name>
	<url>http://maven.apache.org</url>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.1</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>
</project>
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()

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

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

(3)、 bean1属性填充

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

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

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

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

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

 

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

三级缓存提升至二级缓存

 从二级缓存获取bean1

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

三、解决方法

1、去除循环引用

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

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

四、结论

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

  • 18
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值