Spring IOC学习(2)——DefaultSingletonBeanRegistry

DefaultSingletonBeanRegistry:提供单例对象管理能力

/**
  * Internal marker for a null singleton object:
  * used as marker value for concurrent Maps (which don't support null values).
  */
 protected static final Object NULL_OBJECT = new Object();


 /** Logger available to subclasses */
 protected final Log logger = LogFactory.getLog(getClass());

 /** Cache of singleton objects: bean name --> bean instance 
 * name->已经注册完成的单例对象
 */
 private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);

 /** Cache of singleton factories: bean name --> ObjectFactory 
 * name->对象工厂
 */
 private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);

 /** Cache of early singleton objects: bean name --> bean instance 
 * name->未创建完成,提前暴露的对象
 */
 private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);

 /** Set of registered singletons, containing the bean names in registration order 
 * 已经完成注册的单例对象
 */
 private final Set<String> registeredSingletons = new LinkedHashSet<String>(256);

 /** Names of beans that are currently in creation 
 * 当前正在创建的单例对象
 */
 private final Set<String> singletonsCurrentlyInCreation =
   Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));

 /** Names of beans currently excluded from in creation checks 
 * 不进行“当前正在创建”检查的bean
 */
 private final Set<String> inCreationCheckExclusions =
   Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));

 /** List of suppressed Exceptions, available for associating related causes */
 private Set<Exception> suppressedExceptions;

 /** Flag that indicates whether we're currently within destroySingletons 
 * 容器关闭,正在销毁所有单例对象时为true
 */
 private boolean singletonsCurrentlyInDestruction = false;

 /** Disposable bean instances: bean name --> disposable instance 
 * 实现了DisposableBean接口的bean
 */
 private final Map<String, Object> disposableBeans = new LinkedHashMap<String, Object>();

 /** Map between containing bean names: bean name --> Set of bean names that the bean contains 
 * bean->该bean包含的所有对象
 */
 private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<String, Set<String>>(16);

 /** Map between dependent bean names: bean name --> Set of dependent bean names 
 * bean->所有依赖该bean的对象(“谁依赖我”的关系;包括强依赖和弱依赖)
 */
 private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<String, Set<String>>(64);

 /** Map between depending bean names: bean name --> Set of bean names for the bean's dependencies 
 * bean->该bean依赖的所有对象(“我依赖谁“的关系;包括强依赖和弱依赖)
 */
 private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<String, Set<String>>(64);

 /** 
 * 根据beanName获取单例对象
 */
 public Object getSingleton(String beanName) {
  return getSingleton(beanName, true);
 }

/**
  * Return the (raw) singleton object registered under the given name.
  * <p>Checks already instantiated singletons and also allows for an early
  * reference to a currently created singleton (resolving a circular reference).
  * @param beanName the name of the bean to look for
  * @param allowEarlyReference whether early references should be created or not
  * @return the registered singleton object, or {@code null} if none found
  * 获取单例对象;允许获取到未创建完成但是提前暴露的对象,可以用于解决循环依赖问题
  */
 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) {
     //提前暴露集合中也没有&&允许创建;则通过对应的对象工厂来创建
     ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
     if (singletonFactory != null) {
      //工厂创建对象
      singletonObject = singletonFactory.getObject();
      //对象加入到提前暴露集合中
      this.earlySingletonObjects.put(beanName, singletonObject);
      //对象已创建完毕,移除工厂
      this.singletonFactories.remove(beanName);
     }
    }
   }
  }
  return (singletonObject != NULL_OBJECT ? singletonObject : null);
 }

/**
  * Return the (raw) singleton object registered under the given name,
  * creating and registering a new one if none registered yet.
  * @param beanName the name of the bean
  * @param singletonFactory the ObjectFactory to lazily create the singleton
  * with, if necessary
  * @return the registered singleton object
  * 根据beanName获取单例对象;如果对象还未注册,则创建并注册一个新的对象
  */
 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 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 + "'");
    }
    //将该bean加入到正在创建集合中
    beforeSingletonCreation(beanName);
    boolean newSingleton = false;
    boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
    if (recordSuppressedExceptions) {
     this.suppressedExceptions = new LinkedHashSet<Exception>();
    }
    try {
     //新创建对象
     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.
     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) {
     //将新创建的对象注册到已注册集合中
     addSingleton(beanName, singletonObject);
    }
   }
   return (singletonObject != NULL_OBJECT ? singletonObject : null);
  }
 }

/**
 * 判断dependentBeanName是否直接或间接地依赖beanName
 */
 private boolean isDependent(String beanName, String dependentBeanName, Set<String> alreadySeen) {
  if (alreadySeen != null && alreadySeen.contains(beanName)) {
   return false;
  }
  String canonicalName = canonicalName(beanName);
  Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
  if (dependentBeans == null) {
   return false;
  }
  if (dependentBeans.contains(dependentBeanName)) {
   //直接依赖
   return true;
  }
  for (String transitiveDependency : dependentBeans) {
   //判断是否间接依赖
   if (alreadySeen == null) {
    alreadySeen = new HashSet<String>();
   }
   alreadySeen.add(beanName);
   if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
    return true;
   }
  }
  return false;
 }

/**
  * Destroy the given bean. Must destroy beans that depend on the given
  * bean before the bean itself. Should not throw any exceptions.
  * @param beanName the name of the bean
  * @param bean the bean instance to destroy
  * 容器关闭时销毁bean;必须先销毁依赖该bean的bean
  */
 protected void destroyBean(String beanName, DisposableBean bean) {
  // Trigger destruction of dependent beans first...
  Set<String> dependencies;
  synchronized (this.dependentBeanMap) {
   // Within full synchronization in order to guarantee a disconnected Set
   dependencies = this.dependentBeanMap.remove(beanName);
  }
  if (dependencies != null) {
   if (logger.isDebugEnabled()) {
    logger.debug("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
   }
   for (String dependentBeanName : dependencies) {
    //销毁所有依赖该bean的bean
    destroySingleton(dependentBeanName);
   }
  }

  // Actually destroy the bean now...
  //销毁该bean
  if (bean != null) {
   try {
    //执行实现的destroy方法
    bean.destroy();
   }
   catch (Throwable ex) {
    logger.error("Destroy method on bean with name '" + beanName + "' threw an exception", ex);
   }
  }

  // Trigger destruction of contained beans...
  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) {
    //清除该bean包含的所有bean(疑问:contain和depend关系?)
    destroySingleton(containedBeanName);
   }
  }

  // Remove destroyed bean from other beans' dependencies.
  synchronized (this.dependentBeanMap) {
   //清除dependentBeanMap中该bean对其他bean的依赖关系
   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对其他bean的依赖关系
  this.dependenciesForBeanMap.remove(beanName);
 }

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值