这是DefaultSingletonBeanRegistry类的体系结构,由一个类一个责任的原则
- AliasRegistry : 提供别名注册的接口
- SingletonBeanRegistry : 提供单例bean注册的接口
- ObjectFactory : 这个接口通常用于封装一个通用的工厂,它只有一个方法getObject() ,它调用getObject()方法返回一个新的实例,一些在每次调用的目标对象(原型).
- DisposableBean : 接口实现为beans要破坏释放资源。它也只有一个方法destroy(),由一个破坏一个singleton的BeanFactory调用。
- SimpleAliasRegistry: 它简单地实现了AliasRegistry接口。
- DefaultSingletonBeanRegistry:它继承SimpleAliasRegistry类和实现了SingletonBeanRegistry接口,因此这个类可以有别名注册的功能和单例bean注册的功能,并且他还支持注册DisposableBean实例;它依赖ObjectFactory接口和DisposableBean接口(关闭注册表时调用到了destroy方法)。
- <span>/**
- * 共享bean实例的通用注册表,实现了SingletonBeanRegistry. 允许注册表中注册的单例应该被所有调用者共享,通过bean名称获得。
- *
- * 还支持登记的DisposableBean实例,(这可能会或不能正确的注册单例),关闭注册表时destroyed.
- * 可以注册bean之间的依赖关系,执行适当的关闭顺序。
- *
- *
- * 这个类主要用作基类的BeanFactory实现, 提供基本的管理
- * singleton bean 实例功能。
- *
- */
- public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
- SingletonBeanRegistry {
- //内部标记为一个空的单例对象: 并发 Maps( 不支持空值 )作为标志值。
- protected static final Object NULL_OBJECT = new Object();
- // 日记用来记录子类
- protected final Log logger = LogFactory.getLog(getClass());
- //是存放singleton对象的缓存
- private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>();
- // 是存放制造singleton的工厂对象的缓存
- private final Map<String, ObjectFactory> singletonFactories = new HashMap<String, ObjectFactory>();
- //是存放singletonFactory 制造出来的 singleton 的缓存</span><span>
- private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>();
- //以上三个缓存是这个类存放单例bean的主要Map
- //就是单例注册表</span><span>
- private final Set<String> registeredSingletons = new LinkedHashSet<String>(
- 16);
- //目前正在创建中的单例bean的名称的集合</span><span>
- private final Set<String> singletonsCurrentlyInCreation = Collections
- .synchronizedSet(new HashSet<String>());
- //存放异常出现的相关的原因的集合</span><span>
- private Set<Exception> suppressedExceptions;
- //标志,指示我们目前是否在销毁单例中</span><span>
- private boolean singletonsCurrentlyInDestruction = false;
- //存放一次性bean的缓存</span><span>
- private final Map<String, Object> disposableBeans = new LinkedHashMap<String, Object>();
- //外部bean与被包含在外部bean的所有内部bean集合包含关系的缓存
- private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<String, Set<String>>();
- //指定bean与依赖指定bean的所有bean的依赖关系的缓存
- private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<String, Set<String>>();
- //指定bean与创建这个bean所需要依赖的所有bean的依赖关系的缓存</span><span>
- private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<String, Set<String>>();
- // SingletonBeanRegistry接口的registerSingleton方法的实现
- public void registerSingleton(String beanName, Object singletonObject)
- throws IllegalStateException {
- Assert.notNull(beanName, “‘beanName’ must not be null”);
- synchronized (this.singletonObjects) {
- Object oldObject = this.singletonObjects.get(beanName);
- </span><span>//如果singletonObjects缓存找到有指定名称为beanName的对象,则表示该名称已被占用
- if (oldObject != null) {
- throw new IllegalStateException(“Could not register object [“
- + singletonObject + “] under bean name ‘” + beanName
- + “‘: there is already object [“ + oldObject
- + “] bound”);
- }
- </span><span>//若该名称没被占用,真正的注册操作在这里实现
- addSingleton(beanName, singletonObject);
- }
- }
- protected void addSingleton(String beanName, Object singletonObject) {
- synchronized (this.singletonObjects) {
- // 因为singletonObjects类型是ConcurrentHashMap,并发Map不支持空值作为标志值,所以用NULL_OBJECT来代替
- this.singletonObjects.put(beanName,
- (singletonObject != null ? singletonObject : NULL_OBJECT));
- // beanName已被注册存放在singletonObjects缓存,那么singletonFactories不应该再持有名称为beanName的工厂
- this.singletonFactories.remove(beanName);
- // beanName已被注册存放在singletonObjects缓存,那么earlySingletonObjects不应该再持有名称为beanName的bean。
- this.earlySingletonObjects.remove(beanName);
- // beanName放进单例注册表中
- this.registeredSingletons.add(beanName);
- }
- }
- /**
- * 添加 名称为beanName的singletonFactory对象
- *
- */
- protected void addSingletonFactory(String beanName,
- ObjectFactory singletonFactory) {
- Assert.notNull(singletonFactory, “Singleton factory must not be null”);
- synchronized (this.singletonObjects) {
- // 判断singletonObjects内名字为beanName是否被占用,若没有,进行注册操作
- if (!this.singletonObjects.containsKey(beanName)) {
- this.singletonFactories.put(beanName, singletonFactory);
- this.earlySingletonObjects.remove(beanName);
- this.registeredSingletons.add(beanName);
- }
- }
- }
- // SingletonBeanRegistry接口的getSingleton方法的实现
- public Object getSingleton(String beanName) {
- return getSingleton(beanName, true);
- }
- protected Object getSingleton(String beanName, boolean allowEarlyReference) {
- Object singletonObject = this.singletonObjects.get(beanName);
- // 如果singletonObjects指定beanName的对象是不存在的
- if (singletonObject == null) {
- synchronized (this.singletonObjects) {
- singletonObject = this.earlySingletonObjects.get(beanName);
- // 如果earlySingletonObjects指定的beanName的对象是不存在的且allowEarlyReference是允许的
- if (singletonObject == null && allowEarlyReference) {
- ObjectFactory singletonFactory = this.singletonFactories
- .get(beanName);
- // 如果存在指定beanName的singletonFactory对象
- if (singletonFactory != null) {
- // singletonFactory创建指定的单例对象
- singletonObject = singletonFactory.getObject();
- // 这里可以看出earlySingletonObjects缓存应该是存放singletonFactory产生的singleton
- this.earlySingletonObjects.put(beanName,
- singletonObject);
- // 这里表示指定的beanName已被占用,所以要在singletonFactories移除该名称
- this.singletonFactories.remove(beanName);
- }
- }
- }
- }
- return (singletonObject != NULL_OBJECT ? singletonObject : null);
- }
- public Object getSingleton(String beanName, ObjectFactory singletonFactory) {
- Assert.notNull(beanName, “‘beanName’ must not be null”);
- synchronized (this.singletonObjects) {
- Object singletonObject = this.singletonObjects.get(beanName);
- // 如果singetonObjects缓存不存在名称为beanName的对象
- if (singletonObject == null) {
- // 如果目前在销毁singellton
- 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<Exception>();
- }
- try {
- // 由参数给定的singletonFactory创建singleton对象,getObject方法的具体实现由ObjectFactory的子类决定
- 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);
- }
- }
- /**
- * 注册 发生在singeton bean 实例创建之间发生的异常
- */
- protected void onSuppressedException(Exception ex) {
- synchronized (this.singletonObjects) {
- if (this.suppressedExceptions != null) {
- this.suppressedExceptions.add(ex);
- }
- }
- }
- /**
- * 移除名称为beanName的单例,主要在四个集合中移除,
- * 如singletonObjects,singletonFactories,earlySingletonObjects
- * ,registeredSingletons
- *
- */
- protected void removeSingleton(String beanName) {
- synchronized (this.singletonObjects) {
- this.singletonObjects.remove(beanName);
- this.singletonFactories.remove(beanName);
- this.earlySingletonObjects.remove(beanName);
- this.registeredSingletons.remove(beanName);
- }
- }
- // singletonBeanRegistry接口的containsSingleton方法实现
- public boolean containsSingleton(String beanName) {
- return (this.singletonObjects.containsKey(beanName));
- }
- // singletonBeanRegistry接口的getSingletonNames方法实现
- public String[] getSingletonNames() {
- // 对singletonObjects加锁,可能是为了防止registeredSingletons和singletonObjects出现不一致的问题
- synchronized (this.singletonObjects) {
- return StringUtils.toStringArray(this.registeredSingletons);
- }
- }
- // singletonBeanRegistry接口的getSingletonCount方法实现
- public int getSingletonCount() {
- synchronized (this.singletonObjects) {
- return this.registeredSingletons.size();
- }
- }
- /**
- * 单例对象创建前的回调,默认实现singletonsCurrentlyInCreation集合注册正在创建的单例.
- *
- */
- protected void beforeSingletonCreation(String beanName) {
- if (!this.singletonsCurrentlyInCreation.add(beanName)) {
- throw new BeanCurrentlyInCreationException(beanName);
- }
- }
- /**
- * 单例创建之后的回调,默认实现singletonCurrentlyInCreation集合移除正在创建的单例</span><span>
- *
- */
- protected void afterSingletonCreation(String beanName) {
- if (!this.singletonsCurrentlyInCreation.remove(beanName)) {
- throw new IllegalStateException(“Singleton ‘” + beanName
- + “‘ isn’t currently in creation”);
- }
- }
- /**
- * 返回 存放正在创建单例的集合是否包含指定名称为beanName的单例存在
- *
- */
- public final boolean isSingletonCurrentlyInCreation(String beanName) {
- return this.singletonsCurrentlyInCreation.contains(beanName);
- }
- /**
- * 一次性bean注册,存放在disponsableBeans集合中
- *
- */
- public void registerDisposableBean(String beanName, DisposableBean bean) {
- synchronized (this.disposableBeans) {
- this.disposableBeans.put(beanName, bean);
- }
- }
- /**
- * 注册两个bean之间的控制关系,例如内部bean和包含其的外部bean之间
- *
- */
- public void registerContainedBean(String containedBeanName,
- String containingBeanName) {
- synchronized (this.containedBeanMap) {
- // 从containedBeanMap缓存中查找外部bean名为containingBeanName的内部bean集合
- Set<String> containedBeans = this.containedBeanMap
- .get(containingBeanName);
- // 如果没有,刚新建一个存放内部bean的集合,并且存放在containedBeanMap缓存中
- if (containedBeans == null) {
- containedBeans = new LinkedHashSet<String>(8);
- this.containedBeanMap.put(containingBeanName, containedBeans);
- }
- // 将名为containedBeanName的内部bean存放到内部bean集合
- containedBeans.add(containedBeanName);
- }
- // 紧接着调用注册内部bean和外部bean的依赖关系的方法
- registerDependentBean(containedBeanName, containingBeanName);
- }
- /**
- * 注册给定bean的一个依赖bean,给定的bean销毁之前被销毁。
- *
- */
- public void registerDependentBean(String beanName, String dependentBeanName) {
- // 调用SimpleAliasRegistry的canonicalName方法,这方法是将参数beanName当做别名寻找到注册名,并依此递归
- String canonicalName = canonicalName(beanName);
- synchronized (this.dependentBeanMap) {
- // 从dependentBeanMap缓存中找到依赖名为canonicalName这个bean的 依赖bean集合
- Set<String> dependentBeans = this.dependentBeanMap
- .get(canonicalName);
- // 如果为空,则新建一个依赖bean集合,并且存放到dependentBeanMap缓存中
- if (dependentBeans == null) {
- dependentBeans = new LinkedHashSet<String>(8);
- this.dependentBeanMap.put(canonicalName, dependentBeans);
- }
- // 依赖bean集合添加参数2指定的dependentBeanName
- dependentBeans.add(dependentBeanName);
- }
- synchronized (this.dependenciesForBeanMap) {
- // 从dependenciesForBeanMap缓存中找到dependentBeanName要依赖的所有bean集合
- Set<String> dependenciesForBean = this.dependenciesForBeanMap
- .get(dependentBeanName);
- if (dependenciesForBean == null) {
- dependenciesForBean = new LinkedHashSet<String>(8);
- this.dependenciesForBeanMap.put(dependentBeanName,
- dependenciesForBean);
- }
- dependenciesForBean.add(canonicalName);
- }
- }
- /**
- * 确定是否还存在名为beanName的被依赖关系
- */
- protected boolean hasDependentBean(String beanName) {
- return this.dependentBeanMap.containsKey(beanName);
- }
- /**
- * 返回依赖于指定的bean的所有bean的名称,如果有的话。
- *
- */
- public String[] getDependentBeans(String beanName) {
- Set<String> dependentBeans = this.dependentBeanMap.get(beanName);
- if (dependentBeans == null) {
- return new String[0];
- }
- return StringUtils.toStringArray(dependentBeans);
- }
- /**
- * 返回指定的bean依赖于所有的bean的名称,如果有的话。
- *
- */
- public String[] getDependenciesForBean(String beanName) {
- Set<String> dependenciesForBean = this.dependenciesForBeanMap
- .get(beanName);
- // 如果没有的话返回new String[0]而不是null
- if (dependenciesForBean == null) {
- return new String[0];
- }
- return dependenciesForBean.toArray(new String[dependenciesForBean
- .size()]);
- }
- // 销毁单例
- public void destroySingletons() {
- if (logger.isInfoEnabled()) {
- logger.info(“Destroying singletons in “ + this);
- }
- // 单例目前销毁标志开始
- synchronized (this.singletonObjects) {
- this.singletonsCurrentlyInDestruction = true;
- }
- // 销毁disponsableBeans缓存中所有单例bean
- synchronized (this.disposableBeans) {
- String[] disposableBeanNames = StringUtils
- .toStringArray(this.disposableBeans.keySet());
- for (int i = disposableBeanNames.length – 1; i >= 0; i–) {
- destroySingleton(disposableBeanNames[i]);
- }
- }
- // containedBeanMap缓存清空,dependentBeanMap缓存清空,dependenciesForBeanMap缓存清空
- this.containedBeanMap.clear();
- this.dependentBeanMap.clear();
- this.dependenciesForBeanMap.clear();
- // singeltonObjects缓存清空,singletonFactories缓存清空,earlySingletonObjects缓存清空,registeredSingletons缓存清空
- synchronized (this.singletonObjects) {
- this.singletonObjects.clear();
- this.singletonFactories.clear();
- this.earlySingletonObjects.clear();
- this.registeredSingletons.clear();
- // 单例目前正在销毁标志为结束
- this.singletonsCurrentlyInDestruction = false;
- }
- }
- 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) {
- disposableBean = (DisposableBean) this.disposableBeans
- .remove(beanName);
- }
- destroyBean(beanName, disposableBean);
- }
- protected void destroyBean(String beanName, DisposableBean bean) {
- // Trigger destruction of dependent beans first…
- // 这段代码告诉我们先移除要销毁依赖bean
- Set<String> dependencies = this.dependentBeanMap.remove(beanName);
- if (dependencies != null) {
- if (logger.isDebugEnabled()) {
- logger.debug(“Retrieved dependent beans for bean ‘” + beanName
- + “‘: “ + dependencies);
- }
- for (String dependentBeanName : dependencies) {
- destroySingleton(dependentBeanName);
- }
- }
- // Actually destroy the bean now…
- // 销毁bean实例
- if (bean != null) {
- try {
- bean.destroy();
- } catch (Throwable ex) {
- logger.error(“Destroy method on bean with name ‘” + beanName
- + “‘ threw an exception”, ex);
- }
- }
- // Trigger destruction of contained beans…
- // 从containedBeanMap缓存中移除要销毁的bean,递归移除它的包含内部bean集合
- Set<String> containedBeans = this.containedBeanMap.remove(beanName);
- if (containedBeans != null) {
- for (String containedBeanName : containedBeans) {
- destroySingleton(containedBeanName);
- }
- }
- // Remove destroyed bean from other beans’ dependencies.
- // 从其它bean的依赖bean集合中移除要销毁的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);
- if (dependenciesToClean.isEmpty()) {
- it.remove();
- }
- }
- }
- // Remove destroyed bean’s prepared dependency information.
- // 最后 从dependenciesForBeanMap缓存中移除要销毁的bean
- this.dependenciesForBeanMap.remove(beanName);
- }
- /**
- * Expose the singleton mutex to subclasses.
- * <p>
- * Subclasses should synchronize on the given Object if they perform any
- * sort of extended singleton creation phase. In particular, subclasses
- * should <i>not</i> have their own mutexes involved in singleton creation,
- * to avoid the potential for deadlocks in lazy-init situations.
- */
- protected final Object getSingletonMutex() {
- return this.singletonObjects;
- }
- }
- </span>