DefaultSingletonBeanRegistry

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

类结构

截取部分

常量

// 单例对象的缓存:从beanname到bean实例private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);// 单例工厂的缓存:从beanname到ObjectFactoryprivate final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);// 早期单例对象的缓存:从beanname到bean实例private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);// 一组已注册的单例,包含按注册顺序排列的beannameprivate 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为valueprivate final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);// 指定bean与指定bean依赖的集合,比如a依赖bcd,那么就是key为a,bcd为valueprivate 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的信息读取

@Overridepublic boolean containsSingleton(String beanName) {    // 是否已经缓存过    return this.singletonObjects.containsKey(beanName);}@Overridepublic String[] getSingletonNames() {    //获取已经注册过的bean    synchronized (this.singletonObjects) {        return StringUtils.toStringArray(this.registeredSingletons);    }}@Overridepublic 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;}