循环依赖报错 Requested bean is currently in creation: Is there an unresolvable circular reference?

原因

今天做项目遇到了这个坑,字面上看是触发了循环依赖,由于我使用的是构造器注入,所以遇到循环依赖就会导致报错。如图所示,我的依赖链形成了一个环路。
循环依赖报错 Requested bean is currently in creation: Is there an unresolvable circular reference?_第1张图片

为什么构造器注入不行

因为要实现循环依赖就得在A调用B,B再调用A的时候,A提前放入singletonFactories三级缓存,否则A和B都没法实例化。而加入singletonFactories三级缓存的前提是执行了构造器,所以构造器注入的循环依赖没法解决,它重写了构造器。spring源码如下:

 // Eagerly cache singletons to be able to resolve circular references
        // even when triggered by lifecycle interfaces like BeanFactoryAware.
        //向容器中缓存单例模式的Bean对象,以防循环引用
        boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                isSingletonCurrentlyInCreation(beanName));
        if (earlySingletonExposure) {
            if (logger.isDebugEnabled()) {
                logger.debug("Eagerly caching bean '" + beanName +
                        "' to allow for resolving potential circular references");
            }
            //这里是一个匿名内部类,为了防止循环引用,尽早持有对象的引用
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }

    protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
        Assert.notNull(singletonFactory, "Singleton factory must not be null");
        synchronized (this.singletonObjects) {
            if (!this.singletonObjects.containsKey(beanName)) {
                this.singletonFactories.put(beanName, singletonFactory);//三级缓存
                this.earlySingletonObjects.remove(beanName);
                this.registeredSingletons.add(beanName);
            }
        }
    }

解决方案

查看错误日志:

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'refundSettleRespOneByOneBiz': Requested bean is 
currently in creation: Is there an unresolvable circular reference?

到refundSettleRespOneByOneBiz这个类中,将构造器注入改为setter注入
循环依赖报错 Requested bean is currently in creation: Is there an unresolvable circular reference?_第2张图片
修改其中一个节点,这样就打破了循环依赖~

你可能感兴趣的:(spring)