Spring经典函数收集:递归调用

2020-05-11  本文已影响0人  码而优则仕

Spring经典函数收集:递归调用

protected boolean isDependent(String beanName, String dependentBeanName) {
        synchronized (this.dependentBeanMap) {
            return isDependent(beanName, dependentBeanName, null);
        }
    }

    // A-[1,2,3,4],1->[a,b,c,d],2->[q,w,r]....
    //第一次调用 检查A->[1,2,3,4]
    //第一次,一层检查没有循环依赖,则检查 A依赖的每个 bean的依赖集合
    //循环,递归 1->[a,b,c,d] 直到全部检查完毕
    //alreadySeen 存放已经检查过的和当前 bean不循环依赖的bean集合
    private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) {
        if (alreadySeen != null && alreadySeen.contains(beanName)) {
            return false;
        }
        //处理多重别名
        String canonicalName = canonicalName(beanName);
        //获取当前bean依赖的所有bean名称集合
        Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
        if (dependentBeans == null) {
            return false;
        }
        //当前bean 依赖的bean中包含当前bean就是循环依赖
        if (dependentBeans.contains(dependentBeanName)) {
            return true;
        }
        //循环检查当前 bean依赖的 bean集合中的每个 bean依赖的bean集合 是否和当前bean循环依赖
        for (String transitiveDependency : dependentBeans) {
            if (alreadySeen == null) {
                alreadySeen = new HashSet<>();
            }
            alreadySeen.add(beanName);
            //递归调用检查循环依赖
            if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
                return true;
            }
        }
        return false;
    }

上一篇下一篇

猜你喜欢

热点阅读