Spring循环引用踩坑记

项目启动的时候报了如下的错误:

Error creating bean with name 'boingpayCallbackController': Unsatisfied dependency expressed through field 'transitToCashService'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'transitToCashService': Bean with name 'transitToCashService' has been injected into other beans [flowCheckCore,bankFlowCheckService,checkLogService] 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.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
 at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
 at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
 at org.springframework.beans.factory.support.DefaultLis

分析:

看了下报的是循环依赖的错误,但是Spring单例是支持循环依赖的,然后网上搜索发现是因为transitToCashService这个类中的方法有加**@Async**注解(只需要类/方法有标注@Async注解的Bean最终都会生成一个代理对象重新赋值并add进Spring容器内)。

解决办法:

​ 不要让@Async的Bean参与循环依赖

​ 使用@Lazy或者@ComponentScan(lazyInit = true)

​ 通过后置处理器设置allowRawInjectionDespiteWrapping=true(@Aysnc方法将不起作用)

你可能感兴趣的:(Spring,异常,@Async,循环依赖)