DefaultSingletonBeanRegistry源码解析

DefaultSingletonBeanRegistry是SingletionBean注册器的默认实现。

来学习下DefaultSingletonBeanRegistry的源码:

  1 package org.springframework.beans.factory.support;
  2 
  3 import java.util.Collections;
  4 import java.util.HashMap;
  5 import java.util.HashSet;
  6 import java.util.Iterator;
  7 import java.util.LinkedHashMap;
  8 import java.util.LinkedHashSet;
  9 import java.util.Map;
 10 import java.util.Set;
 11 import java.util.concurrent.ConcurrentHashMap;
 12 
 13 import org.apache.commons.logging.Log;
 14 import org.apache.commons.logging.LogFactory;
 15 
 16 import org.springframework.beans.factory.BeanCreationException;
 17 import org.springframework.beans.factory.BeanCreationNotAllowedException;
 18 import org.springframework.beans.factory.BeanCurrentlyInCreationException;
 19 import org.springframework.beans.factory.DisposableBean;
 20 import org.springframework.beans.factory.ObjectFactory;
 21 import org.springframework.beans.factory.config.SingletonBeanRegistry;
 22 import org.springframework.core.SimpleAliasRegistry;
 23 import org.springframework.util.Assert;
 24 import org.springframework.util.StringUtils;
 25 
 26 /**
 27  * Generic registry for shared bean instances, implementing the
 28  * {@link org.springframework.beans.factory.config.SingletonBeanRegistry}.
 29  * Allows for registering singleton instances that should be shared
 30  * for all callers of the registry, to be obtained via bean name.
 31  *
 32  * <p>Also supports registration of
 33  * {@link org.springframework.beans.factory.DisposableBean} instances,
 34  * (which might or might not correspond to registered singletons),
 35  * to be destroyed on shutdown of the registry. Dependencies between
 36  * beans can be registered to enforce an appropriate shutdown order.
 37  *
 38  * <p>This class mainly serves as base class for
 39  * {@link org.springframework.beans.factory.BeanFactory} implementations,
 40  * factoring out the common management of singleton bean instances. Note that
 41  * the {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}
 42  * interface extends the {@link SingletonBeanRegistry} interface.
 43  *
 44  * <p>Note that this class assumes neither a bean definition concept
 45  * nor a specific creation process for bean instances, in contrast to
 46  * {@link AbstractBeanFactory} and {@link DefaultListableBeanFactory}
 47  * (which inherit from it). Can alternatively also be used as a nested
 48  * helper to delegate to.
 49  *
 50  * @author Juergen Hoeller
 51  * @since 2.0
 52  * @see #registerSingleton
 53  * @see #registerDisposableBean
 54  * @see org.springframework.beans.factory.DisposableBean
 55  * @see org.springframework.beans.factory.config.ConfigurableBeanFactory
 56  */
 57 public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
 58 
 59     /**
 60      * Internal marker for a null singleton object:
 61      * used as marker value for concurrent Maps (which don't support null values).
 62      */
 63     //由于Map不能存放null,因此用一个特殊的对象表示null
 64     protected static final Object NULL_OBJECT = new Object();
 65 
 66 
 67     /** Logger available to subclasses */
 68     protected final Log logger = LogFactory.getLog(getClass());
 69 
 70     /** Cache of singleton objects: bean name --> bean instance */
 71     //单例Bean的缓存,bean name 对应 bean 实例
 72     private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
 73 
 74     /** Cache of singleton factories: bean name --> ObjectFactory */
 75     //ObjectFactory的缓存,bean name 对应 特定ObjectFactory;ObjectFactory的getObject方法返回bean的实例 
 76     private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);
 77 
 78     /** Cache of early singleton objects: bean name --> bean instance */
 79     //早期bean实例的缓存, bean name 对应 early bean instance
 80     private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);
 81 
 82     /** Set of registered singletons, containing the bean names in registration order */
 83     //单例bean的注册表
 84     private final Set<String> registeredSingletons = new LinkedHashSet<String>(256);
 85 
 86     /** Names of beans that are currently in creation */
 87     //正在创建的singleton的bean name的集合
 88     private final Set<String> singletonsCurrentlyInCreation =
 89             Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));
 90 
 91     /** Names of beans currently excluded from in creation checks */
 92     //检查正在创建bean时,出去该集合中的bean
 93     private final Set<String> inCreationCheckExclusions =
 94             Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));
 95 
 96     /** List of suppressed Exceptions, available for associating related causes */
 97     //用来存储异常
 98     private Set<Exception> suppressedExceptions;
 99 
100     /** Flag that indicates whether we're currently within destroySingletons */
101     //当前是否有singleton被销毁
102     private boolean singletonsCurrentlyInDestruction = false;
103 
104     /** Disposable bean instances: bean name --> disposable instance */
105     //bean对应的DisposableBean, DisposableBean接口有一个destroy()。为bean指定DisposableBean,作用类似于设置destroy-method
106     private final Map<String, Object> disposableBeans = new LinkedHashMap<String, Object>();
107 
108     /** Map between containing bean names: bean name --> Set of bean names that the bean contains */
109     //bean包含关系的缓存:bean name  对应 该bean包含的所有bean的name
110     private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<String, Set<String>>(16);
111 
112     /** Map between dependent bean names: bean name --> Set of dependent bean names */
113     //bean依赖关系的缓存:bean name 对应 依赖于该bean的所有bean的name (value中bean要先于key表示的bean被销毁)
114     private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<String, Set<String>>(64);
115 
116     /** Map between depending bean names: bean name --> Set of bean names for the bean's dependencies */
117     //bean依赖关系的缓存:bean name 对应 该bean依赖的所有bean的name
118     private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<String, Set<String>>(64);
119 
120 
121 
122     //注册singletion
123     @Override
124     public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
125         Assert.notNull(beanName, "'beanName' must not be null");
126         synchronized (this.singletonObjects) {
127             //如果已经存在,抛出异常
128             Object oldObject = this.singletonObjects.get(beanName);
129             if (oldObject != null) {
130                 throw new IllegalStateException("Could not register object [" + singletonObject +
131                         "] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
132             }
133             addSingleton(beanName, singletonObject);
134         }
135     }
136 
137     /**
138      * Add the given singleton object to the singleton cache of this factory.
139      * <p>To be called for eager registration of singletons.
140      * @param beanName the name of the bean
141      * @param singletonObject the singleton object
142      */
143     //真正的注册实现
144     protected void addSingleton(String beanName, Object singletonObject) {
145         synchronized (this.singletonObjects) {
146             //添加至单例bean的缓存中
147             this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
148             //已经存在该单例bean的实例,因此对应的工厂和earlySingleton不再需要
149             this.singletonFactories.remove(beanName);
150             this.earlySingletonObjects.remove(beanName);
151             //添加进注册表
152             this.registeredSingletons.add(beanName);
153         }
154     }
155 
156     /**
157      * Add the given singleton factory for building the specified singleton
158      * if necessary.
159      * <p>To be called for eager registration of singletons, e.g. to be able to
160      * resolve circular references.
161      * @param beanName the name of the bean
162      * @param singletonFactory the factory for the singleton object
163      */
164     //添加ObjectFactory
165     protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
166         Assert.notNull(singletonFactory, "Singleton factory must not be null");
167         synchronized (this.singletonObjects) {
168             //如果还不存在该bean的实例,则加添对应的ObjectFactory
169             if (!this.singletonObjects.containsKey(beanName)) {
170                 this.singletonFactories.put(beanName, singletonFactory);
171                 this.earlySingletonObjects.remove(beanName);
172                 this.registeredSingletons.add(beanName);
173             }
174         }
175     }
176 
177     //获取bean实例
178     @Override
179     public Object getSingleton(String beanName) {
180         return getSingleton(beanName, true);
181     }
182 
183     /**
184      * Return the (raw) singleton object registered under the given name.
185      * <p>Checks already instantiated singletons and also allows for an early
186      * reference to a currently created singleton (resolving a circular reference).
187      * @param beanName the name of the bean to look for
188      * @param allowEarlyReference whether early references should be created or not
189      * @return the registered singleton object, or {@code null} if none found
190      */
191     protected Object getSingleton(String beanName, boolean allowEarlyReference) {
192         Object singletonObject = this.singletonObjects.get(beanName);
193         //如果beanName对应的实例不存在但是正在创建
194         if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
195             synchronized (this.singletonObjects) {
196                 //获取early的bean实例
197                 singletonObject = this.earlySingletonObjects.get(beanName);
198                 //如果允许创建早期对象,则通过singletionFactory创建
199                 if (singletonObject == null && allowEarlyReference) {
200                     ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
201                     if (singletonFactory != null) {
202                         singletonObject = singletonFactory.getObject();
203                         this.earlySingletonObjects.put(beanName, singletonObject);
204                         //移除对应的ObjectFactory
205                         this.singletonFactories.remove(beanName);
206                     }
207                 }
208             }
209         }
210         return (singletonObject != NULL_OBJECT ? singletonObject : null);
211     }
212 
213     /**
214      * Return the (raw) singleton object registered under the given name,
215      * creating and registering a new one if none registered yet.
216      * @param beanName the name of the bean
217      * @param singletonFactory the ObjectFactory to lazily create the singleton
218      * with, if necessary
219      * @return the registered singleton object
220      */
221     public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
222         Assert.notNull(beanName, "'beanName' must not be null");
223         synchronized (this.singletonObjects) {
224             Object singletonObject = this.singletonObjects.get(beanName);
225             if (singletonObject == null) {
226                 //不允许在有singletion被销毁的时候创建
227                 if (this.singletonsCurrentlyInDestruction) {
228                     throw new BeanCreationNotAllowedException(beanName,
229                             "Singleton bean creation not allowed while singletons of this factory are in destruction " +
230                             "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
231                 }
232                 if (logger.isDebugEnabled()) {
233                     logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
234                 }
235 
236                 beforeSingletonCreation(beanName);
237                 boolean newSingleton = false;
238                 boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
239                 if (recordSuppressedExceptions) {
240                     this.suppressedExceptions = new LinkedHashSet<Exception>();
241                 }
242                 try {
243                     //通过ObjectFactory来获取singleton的实例
244                     singletonObject = singletonFactory.getObject();
245                     newSingleton = true;
246                 }
247                 catch (IllegalStateException ex) {
248                     // Has the singleton object implicitly appeared in the meantime ->
249                     // if yes, proceed with it since the exception indicates that state.
250                     singletonObject = this.singletonObjects.get(beanName);
251                     if (singletonObject == null) {
252                         throw ex;
253                     }
254                 }
255                 catch (BeanCreationException ex) {
256                     if (recordSuppressedExceptions) {
257                         for (Exception suppressedException : this.suppressedExceptions) {
258                             ex.addRelatedCause(suppressedException);
259                         }
260                     }
261                     throw ex;
262                 }
263                 finally {
264                     if (recordSuppressedExceptions) {
265                         this.suppressedExceptions = null;
266                     }
267                     afterSingletonCreation(beanName);
268                 }
269                 //创建成功,则注册实例
270                 if (newSingleton) {
271                     addSingleton(beanName, singletonObject);
272                 }
273             }
274             return (singletonObject != NULL_OBJECT ? singletonObject : null);
275         }
276     }
277 
278     /**
279      * Register an Exception that happened to get suppressed during the creation of a
280      * singleton bean instance, e.g. a temporary circular reference resolution problem.
281      * @param ex the Exception to register
282      */
283     protected void onSuppressedException(Exception ex) {
284         synchronized (this.singletonObjects) {
285             if (this.suppressedExceptions != null) {
286                 this.suppressedExceptions.add(ex);
287             }
288         }
289     }
290 
291     /**
292      * Remove the bean with the given name from the singleton cache of this factory,
293      * to be able to clean up eager registration of a singleton if creation failed.
294      * @param beanName the name of the bean
295      * @see #getSingletonMutex()
296      */
297     //删除注册的singleton
298     protected void removeSingleton(String beanName) {
299         synchronized (this.singletonObjects) {
300             this.singletonObjects.remove(beanName);
301             this.singletonFactories.remove(beanName);
302             this.earlySingletonObjects.remove(beanName);
303             this.registeredSingletons.remove(beanName);
304         }
305     }
306     //是否包含指定的bean name
307     @Override
308     public boolean containsSingleton(String beanName) {
309         return this.singletonObjects.containsKey(beanName);
310     }
311     //获取注册的bean name
312     @Override
313     public String[] getSingletonNames() {
314         synchronized (this.singletonObjects) {
315             return StringUtils.toStringArray(this.registeredSingletons);
316         }
317     }
318 
319     //获取注册的bean的数目
320     @Override
321     public int getSingletonCount() {
322         synchronized (this.singletonObjects) {
323             return this.registeredSingletons.size();
324         }
325     }
326 
327 
328     public void setCurrentlyInCreation(String beanName, boolean inCreation) {
329         Assert.notNull(beanName, "Bean name must not be null");
330         if (!inCreation) {
331             this.inCreationCheckExclusions.add(beanName);
332         }
333         else {
334             this.inCreationCheckExclusions.remove(beanName);
335         }
336     }
337 
338     //判断该bean是否正在被创建
339     public boolean isCurrentlyInCreation(String beanName) {
340         Assert.notNull(beanName, "Bean name must not be null");
341         return (!this.inCreationCheckExclusions.contains(beanName) && isActuallyInCreation(beanName));
342     }
343 
344     protected boolean isActuallyInCreation(String beanName) {
345         return isSingletonCurrentlyInCreation(beanName);
346     }
347 
348     /**
349      * Return whether the specified singleton bean is currently in creation
350      * (within the entire factory).
351      * @param beanName the name of the bean
352      */
353     //判断该bean name 是否正在被创建
354     public boolean isSingletonCurrentlyInCreation(String beanName) {
355         return this.singletonsCurrentlyInCreation.contains(beanName);
356     }
357 
358     /**
359      * Callback before singleton creation.
360      * <p>The default implementation register the singleton as currently in creation.
361      * @param beanName the name of the singleton about to be created
362      * @see #isSingletonCurrentlyInCreation
363      */
364     protected void beforeSingletonCreation(String beanName) {
365         if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
366             throw new BeanCurrentlyInCreationException(beanName);
367         }
368     }
369 
370     /**
371      * Callback after singleton creation.
372      * <p>The default implementation marks the singleton as not in creation anymore.
373      * @param beanName the name of the singleton that has been created
374      * @see #isSingletonCurrentlyInCreation
375      */
376     protected void afterSingletonCreation(String beanName) {
377         if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
378             throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
379         }
380     }
381 
382 
383     /**
384      * Add the given bean to the list of disposable beans in this registry.
385      * <p>Disposable beans usually correspond to registered singletons,
386      * matching the bean name but potentially being a different instance
387      * (for example, a DisposableBean adapter for a singleton that does not
388      * naturally implement Spring's DisposableBean interface).
389      * @param beanName the name of the bean
390      * @param bean the bean instance
391      */
392     //注册一次性Bean
393     public void registerDisposableBean(String beanName, DisposableBean bean) {
394         synchronized (this.disposableBeans) {
395             this.disposableBeans.put(beanName, bean);
396         }
397     }
398 
399     /**
400      * Register a containment relationship between two beans,
401      * e.g. between an inner bean and its containing outer bean.
402      * <p>Also registers the containing bean as dependent on the contained bean
403      * in terms of destruction order.
404      * @param containedBeanName the name of the contained (inner) bean
405      * @param containingBeanName the name of the containing (outer) bean
406      * @see #registerDependentBean
407      */
408     //注册Bean的包含关系,及依赖关系 containedBeanName
409     public void registerContainedBean(String containedBeanName, String containingBeanName) {
410         // A quick check for an existing entry upfront, avoiding synchronization...
411         // 注册依赖关系
412         Set<String> containedBeans = this.containedBeanMap.get(containingBeanName);
413         if (containedBeans != null && containedBeans.contains(containedBeanName)) {
414             return;
415         }
416 
417         // No entry yet -> fully synchronized manipulation of the containedBeans Set
418         synchronized (this.containedBeanMap) {
419             containedBeans = this.containedBeanMap.get(containingBeanName);
420             if (containedBeans == null) {
421                 containedBeans = new LinkedHashSet<String>(8);
422                 this.containedBeanMap.put(containingBeanName, containedBeans);
423             }
424             containedBeans.add(containedBeanName);
425         }
426         registerDependentBean(containedBeanName, containingBeanName);
427     }
428 
429     /**
430      * Register a dependent bean for the given bean,
431      * to be destroyed before the given bean is destroyed.
432      * @param beanName the name of the bean
433      * @param dependentBeanName the name of the dependent bean
434      */
435     //注册依赖于这个bean name的 
436     public void registerDependentBean(String beanName, String dependentBeanName) {
437         // A quick check for an existing entry upfront, avoiding synchronization...
438         String canonicalName = canonicalName(beanName);
439         Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
440         if (dependentBeans != null && dependentBeans.contains(dependentBeanName)) {
441             return;
442         }
443 
444         // No entry yet -> fully synchronized manipulation of the dependentBeans Set
445         // 准备该beanName被依赖的关系
446         synchronized (this.dependentBeanMap) {
447             dependentBeans = this.dependentBeanMap.get(canonicalName);
448             if (dependentBeans == null) {
449                 dependentBeans = new LinkedHashSet<String>(8);
450                 this.dependentBeanMap.put(canonicalName, dependentBeans);
451             }
452             dependentBeans.add(dependentBeanName);
453         }
454         //注册dependentBeanName的依赖关系
455         synchronized (this.dependenciesForBeanMap) {
456             Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName);
457             if (dependenciesForBean == null) {
458                 dependenciesForBean = new LinkedHashSet<String>(8);
459                 this.dependenciesForBeanMap.put(dependentBeanName, dependenciesForBean);
460             }
461             dependenciesForBean.add(canonicalName);
462         }
463     }
464 
465     /**
466      * Determine whether the specified dependent bean has been registered as
467      * dependent on the given bean or on any of its transitive dependencies.
468      * @param beanName the name of the bean to check
469      * @param dependentBeanName the name of the dependent bean
470      * @since 4.0
471      */
472     protected boolean isDependent(String beanName, String dependentBeanName) {
473         return isDependent(beanName, dependentBeanName, null);
474     }
475 
476     private boolean isDependent(String beanName, String dependentBeanName, Set<String> alreadySeen) {
477         if (alreadySeen != null && alreadySeen.contains(beanName)) {
478             return false;
479         }
480         String canonicalName = canonicalName(beanName);
481         Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
482         if (dependentBeans == null) {
483             return false;
484         }
485         if (dependentBeans.contains(dependentBeanName)) {
486             return true;
487         }
488         //递归检查,是否存在传递性的依赖
489         for (String transitiveDependency : dependentBeans) {
490             if (alreadySeen == null) {
491                 alreadySeen = new HashSet<String>();
492             }
493             alreadySeen.add(beanName);
494             if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
495                 return true;
496             }
497         }
498         return false;
499     }
500 
501     /**
502      * Determine whether a dependent bean has been registered for the given name.
503      * @param beanName the name of the bean to check
504      */
505     protected boolean hasDependentBean(String beanName) {
506         return this.dependentBeanMap.containsKey(beanName);
507     }
508 
509     /**
510      * Return the names of all beans which depend on the specified bean, if any.
511      * @param beanName the name of the bean
512      * @return the array of dependent bean names, or an empty array if none
513      */
514     //返回这个Bean依赖的所有bean
515     public String[] getDependentBeans(String beanName) {
516         Set<String> dependentBeans = this.dependentBeanMap.get(beanName);
517         if (dependentBeans == null) {
518             return new String[0];
519         }
520         return StringUtils.toStringArray(dependentBeans);
521     }
522 
523     /**
524      * Return the names of all beans that the specified bean depends on, if any.
525      * @param beanName the name of the bean
526      * @return the array of names of beans which the bean depends on,
527      * or an empty array if none
528      */
529     //返回这个bean依赖的所有bean
530     public String[] getDependenciesForBean(String beanName) {
531         Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName);
532         if (dependenciesForBean == null) {
533             return new String[0];
534         }
535         return dependenciesForBean.toArray(new String[dependenciesForBean.size()]);
536     }
537 
538     //销毁全部的singletion
539     public void destroySingletons() {
540         if (logger.isDebugEnabled()) {
541             logger.debug("Destroying singletons in " + this);
542         }
543         synchronized (this.singletonObjects) {
544             this.singletonsCurrentlyInDestruction = true;
545         }
546 
547         String[] disposableBeanNames;
548         synchronized (this.disposableBeans) {
549             disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
550         }
551         for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
552             destroySingleton(disposableBeanNames[i]);
553         }
554 
555         //清空依赖关系
556         this.containedBeanMap.clear();
557         this.dependentBeanMap.clear();
558         this.dependenciesForBeanMap.clear();
559 
560         //清空缓存
561         synchronized (this.singletonObjects) {
562             this.singletonObjects.clear();
563             this.singletonFactories.clear();
564             this.earlySingletonObjects.clear();
565             this.registeredSingletons.clear();
566             this.singletonsCurrentlyInDestruction = false;
567         }
568     }
569 
570     /**
571      * Destroy the given bean. Delegates to {@code destroyBean}
572      * if a corresponding disposable bean instance is found.
573      * @param beanName the name of the bean
574      * @see #destroyBean
575      */
576     public void destroySingleton(String beanName) {
577         // Remove a registered singleton of the given name, if any.
578         // 清楚几个缓存
579         removeSingleton(beanName);
580 
581         // Destroy the corresponding DisposableBean instance.
582         // 查找该Bean对应的临时性bean
583         DisposableBean disposableBean;
584         synchronized (this.disposableBeans) {
585             disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
586         }
587         destroyBean(beanName, disposableBean);
588     }
589 
590     /**
591      * Destroy the given bean. Must destroy beans that depend on the given
592      * bean before the bean itself. Should not throw any exceptions.
593      * @param beanName the name of the bean
594      * @param bean the bean instance to destroy
595      */
596     protected void destroyBean(String beanName, DisposableBean bean) {
597         // Trigger destruction of dependent beans first...
598         // 返回依赖于这个beanName的所有Bean,先一步销毁
599         Set<String> dependencies = this.dependentBeanMap.remove(beanName);
600         if (dependencies != null) {
601             if (logger.isDebugEnabled()) {
602                 logger.debug("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
603             }
604             for (String dependentBeanName : dependencies) {
605                 destroySingleton(dependentBeanName);
606             }
607         }
608 
609         // Actually destroy the bean now...
610         //调用destroy方法,用来释放资源等
611         if (bean != null) {
612             try {
613                 bean.destroy();
614             }
615             catch (Throwable ex) {
616                 logger.error("Destroy method on bean with name '" + beanName + "' threw an exception", ex);
617             }
618         }
619 
620         // Trigger destruction of contained beans...
621         // 清除需要包含这个bean的所有Bean
622         Set<String> containedBeans = this.containedBeanMap.remove(beanName);
623         if (containedBeans != null) {
624             for (String containedBeanName : containedBeans) {
625                 destroySingleton(containedBeanName);
626             }
627         }
628 
629         // Remove destroyed bean from other beans' dependencies.
630         // 从其他bean的依赖关系中清除这个bean name
631         synchronized (this.dependentBeanMap) {
632             for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) {
633                 Map.Entry<String, Set<String>> entry = it.next();
634                 Set<String> dependenciesToClean = entry.getValue();
635                 dependenciesToClean.remove(beanName);
636                 if (dependenciesToClean.isEmpty()) {
637                     it.remove();
638                 }
639             }
640         }
641 
642         // Remove destroyed bean's prepared dependency information.
643         // 清除这个bean所依赖的缓存
644         this.dependenciesForBeanMap.remove(beanName);
645     }
646 
647     /**
648      * Exposes the singleton mutex to subclasses and external collaborators.
649      * <p>Subclasses should synchronize on the given Object if they perform
650      * any sort of extended singleton creation phase. In particular, subclasses
651      * should <i>not</i> have their own mutexes involved in singleton creation,
652      * to avoid the potential for deadlocks in lazy-init situations.
653      */
654     public final Object getSingletonMutex() {
655         return this.singletonObjects;
656     }
657 
658 }

DefaultSingletonBeanRegistry主要是通过内部的几个map对象(SingletonFactories,earlySingletonObjects,singletonObjects)来保存注册的Bean。

对应关系是:

  SingletonFactories维护了这个beanName的ObjectFactory。ObjectFactory通过getObject方法获取到了earlySingletonBean,然后在由earlySingletonBean成为bean的实例。

各个SingletonObject之间的关系也是由几个map对象维护(containedBeanMap,dependentBeanMap,dependenciesForBeanMap)。

containedBeanMap(被包含关系:key被value所包含):key是被包含的bean, value则是包含该Bean的所有的bean。(在发现销毁时:value也要被销毁)

dependentBeanMap(被依赖关系:key被value锁依赖):key是被依赖的bean,value则是依赖于该bean的所有bean。(在发生销毁时:value要先于bean被销毁)

dependenciesForBeanMap(依赖关系:key依赖于value):key表示的bean依赖于value表示的Bean。

在注册两个bean包含关系的时候,同时要注册他们的依赖关系。

原文地址:https://www.cnblogs.com/insaneXs/p/7811273.html