乐趣区

spring学习之源码分析DefaultSingletonBeanRegistry

DefaultSingletonBeanRegistry

DefaultSingletonBeanRegistry 类继承了 SimpleAliasRegistry 以及实现了 SingletonBeanRegistry 的接口。处理 Bean 的注册, 销毁, 以及依赖关系的注册和销毁。

类结构

截取部分

常量

// 单例对象的缓存: 从 beanname 到 bean 实例
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
// 单例工厂的缓存: 从 beanname 到 ObjectFactory
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
// 早期单例对象的缓存: 从 beanname 到 bean 实例
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
// 一组已注册的单例,包含按注册顺序排列的 beanname
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
// 正在创建的单例的 beanName 的集合
private final Set<String> singletonsCurrentlyInCreation = Collections.newSetFromMap(new ConcurrentHashMap<>(16));
// 当前不检查的 bean 的集合
private final Set<String> inCreationCheckExclusions = Collections.newSetFromMap(new ConcurrentHashMap<>(16));
// 异常集合
private Set<Exception> suppressedExceptions;
// 当前是否在销毁 bean 中
private boolean singletonsCurrentlyInDestruction = false;
// 一次性 bean 实例
private final Map<String, Object> disposableBeans = new LinkedHashMap<>();
// 内部 bean 和外部 bean 之间关系
private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);
// 指定 bean 与依赖指定 bean 的集合,比如 bcd 依赖 a,那么就是 key 为 a,bcd 为 value
private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);
// 指定 bean 与指定 bean 依赖的集合,比如 a 依赖 bcd,那么就是 key 为 a,bcd 为 value
private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);

方法解析

registerSingleton

通过 bean 的名称和对象进行注册。

public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {Assert.notNull(beanName, "Bean name must not be null");
    Assert.notNull(singletonObject, "Singleton object must not be null");
    synchronized (this.singletonObjects) {Object oldObject = this.singletonObjects.get(beanName);
        // 如果缓存有,说明已经注册过
        if (oldObject != null) {
            throw new IllegalStateException("Could not register object [" + singletonObject +
                    "] under bean name'" + beanName + "': there is already object [" + oldObject + "] bound");
        }
        // 缓存没有,开始注册
        addSingleton(beanName, singletonObject);
    }
}

addSingleton

单例加入到缓存中

protected void addSingleton(String beanName, Object singletonObject) {synchronized (this.singletonObjects) {
        // 加入单例对象的缓存
        this.singletonObjects.put(beanName, singletonObject);
        // 既然加入了单例对象的缓存,那 singletonFactories 和 earlySingletonObjects 就不再持有
        this.singletonFactories.remove(beanName);
        this.earlySingletonObjects.remove(beanName);
        // 加入已注册的 bean
        this.registeredSingletons.add(beanName);
    }
}

addSingletonFactory

// 增加单例工程的单例,取单例的时候调用 getObject 方法
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);
        }
    }
}

getSingleton

public Object getSingleton(String beanName) {return getSingleton(beanName, true);
}
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    // 如果缓存有直接返回
    Object singletonObject = this.singletonObjects.get(beanName);
    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {// 缓存没有的情况且正在创建
        synchronized (this.singletonObjects) {singletonObject = this.earlySingletonObjects.get(beanName);// 如果早期缓存中有,直接返回
            if (singletonObject == null && allowEarlyReference) {//allowEarlyReference 允许是否从 singletonFactories 读取
                ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                if (singletonFactory != null) {// 如果单例工程有,调用 getObject 方法返回
                    singletonObject = singletonFactory.getObject();
                    // singletonFactories 产生的对象放入 earlySingletonObjects 中
                    this.earlySingletonObjects.put(beanName, singletonObject);
                    // 已经产生过一次对象了,所以就不能再用了,后面直接用 earlySingletonObjects 获取
                    this.singletonFactories.remove(beanName);
                }
            }
        }
    }
    return singletonObject;
}

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {Assert.notNull(beanName, "Bean name must not be null");
    synchronized (this.singletonObjects) {Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null) {
            // 当前在销毁 bean,不能创建
            if (this.singletonsCurrentlyInDestruction) {
                throw new BeanCreationNotAllowedException(beanName,
                        "Singleton bean creation not allowed while 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 newSingleton = false;
            // 如果当前没有异常,初始化异常集合
            boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
            if (recordSuppressedExceptions) {this.suppressedExceptions = new LinkedHashSet<>();
            }
            try {
                // 通过 ObjectFactory 的 getObject 创建 bean
                singletonObject = singletonFactory.getObject();
                newSingleton = true;
            }
            catch (IllegalStateException ex) {
                // Has the singleton object implicitly appeared in the meantime ->
                // if yes, proceed with it since the exception indicates that state.
                // 有可能是其他方式创建的 bean
                singletonObject = this.singletonObjects.get(beanName);
                if (singletonObject == null) {throw ex;}
            }
            catch (BeanCreationException ex) {if (recordSuppressedExceptions) {for (Exception suppressedException : this.suppressedExceptions) {ex.addRelatedCause(suppressedException);
                    }
                }
                throw ex;
            }
            finally {if (recordSuppressedExceptions) {this.suppressedExceptions = null;}
                // 创建后检查
                afterSingletonCreation(beanName);
            }
            if (newSingleton) {
                // 是新创建的 bean,就加入到缓存中,如果是其他方式创建的 bean,说明已经加入过缓存了,这边不再加入
                addSingleton(beanName, singletonObject);
            }
        }
        return singletonObject;
    }
}

onSuppressedException

注册过程中发生的异常,加入到异常集合

protected void onSuppressedException(Exception ex) {synchronized (this.singletonObjects) {if (this.suppressedExceptions != null) {this.suppressedExceptions.add(ex);
        }
    }
}

removeSingleton

移除单例,这四个同时移除

protected void removeSingleton(String beanName) {synchronized (this.singletonObjects) {this.singletonObjects.remove(beanName);
        this.singletonFactories.remove(beanName);
        this.earlySingletonObjects.remove(beanName);
        this.registeredSingletons.remove(beanName);
    }
}

containsSingleton

getSingletonNames

getSingletonCount

singletonObjects、registeredSingletons 的信息读取

@Override
public boolean containsSingleton(String beanName) {
    // 是否已经缓存过
    return this.singletonObjects.containsKey(beanName);
}

@Override
public String[] getSingletonNames() {
    // 获取已经注册过的 bean
    synchronized (this.singletonObjects) {return StringUtils.toStringArray(this.registeredSingletons);
    }
}

@Override
public int getSingletonCount() {
    // 获取单例的个数
    synchronized (this.singletonObjects) {return this.registeredSingletons.size();
    }
}

setCurrentlyInCreation

设置不检查的 beanName

public void setCurrentlyInCreation(String beanName, boolean inCreation) {Assert.notNull(beanName, "Bean name must not be null");
    if (!inCreation) {this.inCreationCheckExclusions.add(beanName);
    }
    else {this.inCreationCheckExclusions.remove(beanName);
    }
}

isCurrentlyInCreation

isActuallyInCreation

isSingletonCurrentlyInCreation

是否当前创建的 bean

public boolean isCurrentlyInCreation(String beanName) {Assert.notNull(beanName, "Bean name must not be null");
    // 如果这个 beanName 在不检查集合里,返回 false,说明当前没有创建
    // 如果这个 beanName 要检查,那就要返回是否是正在创建的 bean
    return (!this.inCreationCheckExclusions.contains(beanName) && isActuallyInCreation(beanName));
}
protected boolean isActuallyInCreation(String beanName) {return isSingletonCurrentlyInCreation(beanName);
}
public boolean isSingletonCurrentlyInCreation(String beanName) {return this.singletonsCurrentlyInCreation.contains(beanName);
}

beforeSingletonCreation

afterSingletonCreation

protected void beforeSingletonCreation(String beanName) {
    // 如果这个 beanName 要检查,看看 add 的时候返回什么,如果返回 false,说明已经在创建了,抛异常
    if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {throw new BeanCurrentlyInCreationException(beanName);
    }
}

protected void afterSingletonCreation(String beanName) {
    // 如果这个 beanName 要检查,看看 remove 返回什么,如果返回 false,说明已经创建完了。if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {throw new IllegalStateException("Singleton'" + beanName + "'isn't currently in creation");
    }
}

registerDisposableBean

注册一次性 bean 实例

public void registerDisposableBean(String beanName, DisposableBean bean) {synchronized (this.disposableBeans) {this.disposableBeans.put(beanName, bean);
    }
}

registerContainedBean

public void registerContainedBean(String containedBeanName, String containingBeanName) {synchronized (this.containedBeanMap) {
        // 如果没有 key 为 containingBeanName 的 value,说明内部 bean 集合为空,则初始化一个
        Set<String> containedBeans =
                this.containedBeanMap.computeIfAbsent(containingBeanName, k -> new LinkedHashSet<>(8));
        // 如果已经存在了对应关系,则直接返回,不存在,就添加对应关系
        if (!containedBeans.add(containedBeanName)) {return;}
    }
    registerDependentBean(containedBeanName, containingBeanName);
}

registerDependentBean

canonicalName 方法是属于 SimpleAliasRegistry 的方法。

public void registerDependentBean(String beanName, String dependentBeanName) {String canonicalName = canonicalName(beanName);

    synchronized (this.dependentBeanMap) {
        Set<String> dependentBeans =
                this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
        // 如果已经存在了对应关系,则直接返回, 不存在,就添加对应关系
        if (!dependentBeans.add(dependentBeanName)) {return;}
    }

    synchronized (this.dependenciesForBeanMap) {
        Set<String> dependenciesForBean =
                this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
        // 添加对应关系
        dependenciesForBean.add(canonicalName);
    }
}

isDependent

dependentBeanName 是否依赖 beanName

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

private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) {if (alreadySeen != null && alreadySeen.contains(beanName)) {return false;}
    String canonicalName = canonicalName(beanName);
    Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
    // 为空,说明没有 bean 依赖 beanName,直接返回 false
    if (dependentBeans == null) {return false;}
    // 有其他 bean 依赖 beanName,且包含了 dependentBeanName,返回 true
    if (dependentBeans.contains(dependentBeanName)) {return true;}
    // 有其他 bean 依赖 beanName,但是不包含 dependentBeanName
    for (String transitiveDependency : dependentBeans) {if (alreadySeen == null) {alreadySeen = new HashSet<>();
        }
        alreadySeen.add(beanName);
        // 是否有循环依赖
        if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {return true;}
    }
    return false;
}

hasDependentBean

是否有其他对象依赖指定 bean

protected boolean hasDependentBean(String beanName) {return this.dependentBeanMap.containsKey(beanName);
}

getDependentBeans

返回依赖指定 bean 的数组

public String[] getDependentBeans(String beanName) {Set<String> dependentBeans = this.dependentBeanMap.get(beanName);
    if (dependentBeans == null) {return new String[0];
    }
    synchronized (this.dependentBeanMap) {return StringUtils.toStringArray(dependentBeans);
    }
}

getDependenciesForBean

返回指定 bean,依赖其他 bean 的数组

public String[] getDependenciesForBean(String beanName) {Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName);
    if (dependenciesForBean == null) {return new String[0];
    }
    synchronized (this.dependenciesForBeanMap) {return StringUtils.toStringArray(dependenciesForBean);
    }
}

destroySingletons

销毁单例

public void destroySingletons() {if (logger.isTraceEnabled()) {logger.trace("Destroying singletons in" + this);
    }
    // 设置当前正在销毁
    synchronized (this.singletonObjects) {this.singletonsCurrentlyInDestruction = true;}

    String[] disposableBeanNames;
    synchronized (this.disposableBeans) {disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
    }
    // 销毁 disposableBeans 中的所有 bean
    for (int i = disposableBeanNames.length - 1; i >= 0; i--) {destroySingleton(disposableBeanNames[i]);
    }
    // 清空 containedBeanMap、dependentBeanMap、dependenciesForBeanMap
    this.containedBeanMap.clear();
    this.dependentBeanMap.clear();
    this.dependenciesForBeanMap.clear();
    // 清除单例缓存
    clearSingletonCache();}

clearSingletonCache

清除单例缓存

protected void clearSingletonCache() {synchronized (this.singletonObjects) {this.singletonObjects.clear();
        this.singletonFactories.clear();
        this.earlySingletonObjects.clear();
        this.registeredSingletons.clear();
        // 清除完后,标志恢复为 false
        this.singletonsCurrentlyInDestruction = false;
    }
}

destroySingleton

销毁单例 bean

public void destroySingleton(String beanName) {
    // Remove a registered singleton of the given name, if any.
    // 从缓存中移除
    removeSingleton(beanName);

    // Destroy the corresponding DisposableBean instance.
    DisposableBean disposableBean;
    synchronized (this.disposableBeans) {
        // 从 disposableBeans 移除,如果有 beanName 对应的对象,返回这个对象
        disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
    }
    // 消耗 bean
    destroyBean(beanName, disposableBean);
}

destroyBean

消耗 bean

protected void destroyBean(String beanName, @Nullable DisposableBean bean) {
    // Trigger destruction of dependent beans first...
    Set<String> dependencies;
    // 移除依赖当前 beanName 的 bean
    synchronized (this.dependentBeanMap) {
        // Within full synchronization in order to guarantee a disconnected Set
        // 获取依赖当前 beanName 的 bean
        dependencies = this.dependentBeanMap.remove(beanName);
    }
    if (dependencies != null) {if (logger.isTraceEnabled()) {logger.trace("Retrieved dependent beans for bean'" + beanName + "':" + dependencies);
        }
        // 移除依赖当前 beanName 的 bean
        for (String dependentBeanName : dependencies) {destroySingleton(dependentBeanName);
        }
    }

    // Actually destroy the bean now...
    if (bean != null) {
        try {
            // 销毁 bean
            bean.destroy();}
        catch (Throwable ex) {if (logger.isInfoEnabled()) {logger.info("Destroy method on bean with name'" + beanName + "'threw an exception", ex);
            }
        }
    }

    // Trigger destruction of contained beans...
    // 异常 beanName 的对应关系的 bean
    Set<String> containedBeans;
    synchronized (this.containedBeanMap) {
        // Within full synchronization in order to guarantee a disconnected Set
        containedBeans = this.containedBeanMap.remove(beanName);
    }
    if (containedBeans != null) {for (String containedBeanName : containedBeans) {destroySingleton(containedBeanName);
        }
    }

    // Remove destroyed bean from other beans' dependencies.
    // 这个对象被其他 bean 依赖,也要移除依赖关系
    synchronized (this.dependentBeanMap) {for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) {Map.Entry<String, Set<String>> entry = it.next();
            Set<String> dependenciesToClean = entry.getValue();
            dependenciesToClean.remove(beanName);
            // 如果除了当前的 beanName,没有其他依赖了,直接删除
            if (dependenciesToClean.isEmpty()) {it.remove();
            }
        }
    }

    // Remove destroyed bean's prepared dependency information.
    // 移除当前 bean 与依赖其他 bean 的关系
    this.dependenciesForBeanMap.remove(beanName);
}

getSingletonMutex

用于加锁操作,返回 singletonObjects,通过方法暴露这个对象。

public final Object getSingletonMutex() {return this.singletonObjects;}
退出移动版