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
總結
以上是生活随笔為你收集整理的DefaultSingletonBeanRegistry源码解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: git 分支处理
- 下一篇: 【bzoj1026】[SCOI2009]