什么是循环依赖?
BeanA依赖BeanB,BeanB依赖BeanA。
以此类推
BeanA依赖BeanB,BeanB依赖BeanC,BeanC依赖BeanA。
项目中没有使用构造器注入的方式。理论上不会出现循环依赖。
public class appUserService {
@Autowired
private BalanceCashOutJobService balanceCashOutJobService;
@Autowired
private DistributionPersonnelService distributionPersonnelService;
......
代码略
}
出现报错
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'appUserService': Bean with name 'appUserService' has been injected into other beans [balanceCashOutJobService,distributionPersonnelService] 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:622)
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.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1248)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1168)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
... 45 common frames omitted
解决
经过排查,在configuration配置类里使用了 BeanPostProcessor
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
参考
//www.greatytc.com/p/f17882274dda?from=timeline&isappinstalled=0
BeanPostProcessor接口是用来对bean进行后置处理的,这个时候bean已经完成实例化和依赖注入了,属于bean初始化生命周期的一部分。
当有循环依赖出现时,Bean中注入的bean不是最终的版本,而是spring 三级缓存中的第二级缓存引用。然而这个引用在完成bean注入后将发生改变。导致注入的bean跟最终生成的bean不是同一个。