spring4 IOC循环依赖问题

1. 情况1:setter循环依赖

    
        
    

    
        
    

2. 情况2:构造器循环依赖

    
        
    

    
        
    

spring4 IOC获取单例对象方式

循环依赖只出现在单例模式中,如果是原型模式,那么每次需要依赖对象直接创建新对象,也就不会出现循环依赖问题了。

// 使用给定的名称注册单例对象
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    // 检查缓存中是否存在实例
    Object singletonObject = this.singletonObjects.get(beanName);
    // 如果不存在并且判断当前单例方式创建beanName
    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
        // 给缓存上锁
        synchronized (this.singletonObjects) {
            // 如果此beanName对应的bean实例正在加载则不会再处理
            singletonObject = this.earlySingletonObjects.get(beanName);
            // 如果单例对象为空并且允许早期依赖
            if (singletonObject == null && allowEarlyReference) {
                // 获取beanName对应的单例bean工厂
                ObjectFactory singletonFactory = this.singletonFactories.get(beanName);
                // 单例bean工厂不为空
                if (singletonFactory != null) {
                    // 调用预先设定的getObject方法
                    singletonObject = singletonFactory.getObject();
                    // 将单例bean设置在earlySingletonObjects缓存中
                    this.earlySingletonObjects.put(beanName, singletonObject);
                    // 将单例bean从earlySingletonObjects缓存中移除
                    this.singletonFactories.remove(beanName);
                }
            }
        }
    }
    return (singletonObject != NULL_OBJECT ? singletonObject : null);
}

循环依赖的三级缓存:
① singletonObjects:一级缓存
② earlySingletonObjects:二级缓存
③ singletonFactories:三级缓存,单例bean工厂缓存,缓存singletonFactory

说明:

  1. 如果singletonObjects缓存中已经存在单例bean,直接返回。
  2. 否则查找earlySingletonObjects缓存中是否已经存在单例bean,如果存在,什么也不操作。
  3. 如果不存在,那么通过beanName获取singletonFactories缓存中的singletonFactory单例工厂。
  4. 单例工厂不为空,那么就singletonFactory.getObject()方法创建singletonObject,然后设置到earlySingletonObjects缓存(二级缓存)中,从singletonFactories缓存中移除。

spring4 解决setter循环依赖

beanC和beanD通过setter方式相互依赖,spring4 IOC通过提前曝光的方式来解决循环依赖。

    // 向容器中缓存单例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, new ObjectFactory() {
            @Override
            public Object getObject() throws BeansException {
                return getEarlyBeanReference(beanName, mbd, bean);
            }
        });
    }
    // 向singletonFactories缓存设置singletonFactory
    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);
            }
        }
    }
 
 

说明:
将实例对象实例化之后(createBeanInstance),spring采用提前曝光的方式,将生产bean的工厂singletonFactory,缓存到singletonFactories中。(将实例化对象开了个后门,可以提前获取到实例对象)

设置到一级缓存singletonObjects

重载getSingleton方法来实现设置一级缓存
入口:AbstractBeanFactory中doGetBean方法

// 创建单例Bean的实例对象
if (mbd.isSingleton()) {
    // 获取到单例bean(匿名内部类方式实现) 
    sharedInstance = getSingleton(beanName, new ObjectFactory() {
        @Override
        public Object getObject() throws BeansException {
            try {
                // 创建一个指定Bean实例对象,如果有父级继承,则合并子类和父类的定义
                return createBean(beanName, mbd, args);
            }
            catch (BeansException ex) {
                // 如果捕获到异常,那么就清除缓存中bean名称对应的bean实例
                destroySingleton(beanName);
                throw ex;
            }
        }
    });
    // 获取给定Bean的实例对象
    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

// 获取一个注册成功的单例对象
public Object getSingleton(String beanName, ObjectFactory singletonFactory) {
    Assert.notNull(beanName, "'beanName' must not be null");
    synchronized (this.singletonObjects) {
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null) {
            if (this.singletonsCurrentlyInDestruction) {
                throw new BeanCreationNotAllowedException(beanName,
                        "Singleton bean creation not allowed while the singletons of this factory are in destruction " +
                        "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
            }
            beforeSingletonCreation(beanName);
            boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
            if (recordSuppressedExceptions) {
                this.suppressedExceptions = new LinkedHashSet();
            }
            try {
                singletonObject = singletonFactory.getObject();
            }
            catch (BeanCreationException ex) {
                if (recordSuppressedExceptions) {
                    for (Exception suppressedException : this.suppressedExceptions) {
                        ex.addRelatedCause(suppressedException);
                    }
                }
                throw ex;
            }
            finally {
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = null;
                }
                afterSingletonCreation(beanName);
            }
            addSingleton(beanName, singletonObject);
        }
        return (singletonObject != NULL_OBJECT ? singletonObject : null);
    }
}
 
 

核心实现设置一级缓存singletonObjects的addSingleton方法:

protected void addSingleton(String beanName, Object singletonObject) {
    synchronized (this.singletonObjects) {
        this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
        this.singletonFactories.remove(beanName);
        this.earlySingletonObjects.remove(beanName);
        this.registeredSingletons.add(beanName);
    }
}

循环依赖的流程

  1. 先通过createBeanInstance方法实例化beanC,然后提前曝光,将beanC曝光到singletonFactories缓存中。获取属性beanD,发现beanD未实例化,然后使用getBean方法实例化属性beanD。
  2. beanD实例化过程中,依赖属singletonObjects性beanC,通过getSingleton方法获取,singletonObjects和earlySingletonObjects缓存都没有,但是singletonFactories缓存由于之前的曝光,存在beanC,那么getObject方法直接拿到beanC,并且缓存到earlySingletonObjects中,最后在addSingleton方法缓存到singletonObjects,清空singletonFactories、earlySingletonObjects缓存,beanD实例化完毕。
  3. beanC将拿到实例化属性beanD,那么将执行populateBean方法完成属性值注入,将自身beanC通过ddSingleton方法缓存到singletonObjects中。

你可能感兴趣的:(spring4 IOC循环依赖问题)