1 public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry { 2 3 protected static final Object NULL_OBJECT = new Object();//空object 4 5 6 /** Logger available to subclasses */ 7 protected final Log logger = LogFactory.getLog(getClass()); 8 9 /** 单例缓存: bean name --> bean instance */ 10 private final Map singletonObjects = new ConcurrentHashMap (64); 11 12 /** 单例工厂缓存: bean name --> ObjectFactory */ 13 private final Map singletonFactories = new HashMap (16); 14 15 /** 早期单例对象缓存: bean name --> bean instance */ 16 private final Map earlySingletonObjects = new HashMap (16); 17 18 /** 注册过的单例类(单例工厂) */ 19 private final Set registeredSingletons = new LinkedHashSet (64); 20 21 /** 即将创建的单例类 (using a ConcurrentHashMap as a Set) */ 22 private final Map singletonsCurrentlyInCreation = new ConcurrentHashMap (16); 23 24 /** 正在创建的单例类 (using a ConcurrentHashMap as a Set) */ 25 private final Map inCreationCheckExclusions = new ConcurrentHashMap (16); 26 27 /** 被压制的异常集合 */ 28 private Set suppressedExceptions; 29 30 /** 单例类是否真正被销毁 */ 31 private boolean singletonsCurrentlyInDestruction = false; 32 33 /** Disposable接口的实例: bean name --> disposable instance */ 34 private final Map = new LinkedHashMap (); 35 36 /** bean名称和bean所有包含的Bean的名称的map: bean name --> Set of bean names that the bean contains */ 37 private final Map > containedBeanMap = new ConcurrentHashMap >(16); 38 39 /** bean名称和所有依赖于Bean的名称的map: bean name --> Set of dependent bean names */ 40 private final Map > dependentBeanMap = new ConcurrentHashMap >(64); 41 42 /** bean名称和bean所依赖的所有名称的map --> Set of bean names for the bean's dependencies */ 43 private final Map > dependenciesForBeanMap = new ConcurrentHashMap >(64); 44 45 //SingletonBeanRegistry接口的实现类————注册单例Bean,不能重复注册 46 public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException { 47 Assert.notNull(beanName, "'beanName' must not be null"); 48 synchronized (this.singletonObjects) { 49 Object oldObject = this.singletonObjects.get(beanName); 50 if (oldObject != null) { 51 throw new IllegalStateException("Could not register object [" + singletonObject + 52 "] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound"); 53 } 54 addSingleton(beanName, singletonObject); 55 } 56 } 57 58 //注册一个单例类,注册之后,从singletonFactories、earlySingletonObjects中删去 59 protected void addSingleton(String beanName, Object singletonObject) { 60 synchronized (this.singletonObjects) { 61 this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT)); 62 this.singletonFactories.remove(beanName); 63 this.earlySingletonObjects.remove(beanName);// 64 this.registeredSingletons.add(beanName);//加入,注册过的单例类集合 65 } 66 } 67 68 //注册一个单例工厂类,注册后从earlySingletonObjects移除 69 protected void addSingletonFactory(String beanName, ObjectFactory singletonFactory) { 70 Assert.notNull(singletonFactory, "Singleton factory must not be null"); 71 synchronized (this.singletonObjects) { 72 if (!this.singletonObjects.containsKey(beanName)) { //单例工厂类不能和单例类同名 73 this.singletonFactories.put(beanName, singletonFactory); 74 this.earlySingletonObjects.remove(beanName); 75 this.registeredSingletons.add(beanName); 76 } 77 } 78 } 79 80 //SingletonBeanRegistry接口的实现类 81 public Object getSingleton(String beanName) { 82 return getSingleton(beanName, true); 83 } 84 85 //根据beanName返回单例类 86 protected Object getSingleton(String beanName, boolean allowEarlyReference) { 87 Object singletonObject = this.singletonObjects.get(beanName); 88 if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { // 如果取不到,且该bean正在创建 89 synchronized (this.singletonObjects) { 90 singletonObject = this.earlySingletonObjects.get(beanName); 91 if (singletonObject == null && allowEarlyReference) { // 如果从早期单例缓存中获取不到,且允许早期引用 92 ObjectFactory singletonFactory = this.singletonFactories.get(beanName); // 那么就从单例工厂缓存中获取单例工厂 93 if (singletonFactory != null) { // 如果还是获取不到,就创建一个单例工厂,并把它放进早期单例缓存中,并返回 94 singletonObject = singletonFactory.getObject(); 95 this.earlySingletonObjects.put(beanName, singletonObject); 96 this.singletonFactories.remove(beanName); 97 } 98 } 99 }100 }101 return (singletonObject != NULL_OBJECT ? singletonObject : null);102 }103 104 //获取指定的单例Bean,如果取不到就调用指定的singletonFactory的getObject来返回105 public Object getSingleton(String beanName, ObjectFactory singletonFactory) {106 Assert.notNull(beanName, "'beanName' must not be null");107 synchronized (this.singletonObjects) {108 Object singletonObject = this.singletonObjects.get(beanName);//从单例缓存中获取109 if (singletonObject == null) {110 if (this.singletonsCurrentlyInDestruction) { //如果单例类正在被销毁,就抛出异常111 throw new BeanCreationNotAllowedException(beanName,112 "Singleton bean creation not allowed while the singletons of this factory are in destruction " +113 "(Do not request a bean from a BeanFactory in a destroy method implementation!)");114 }115 if (logger.isDebugEnabled()) {116 logger.debug("Creating shared instance of singleton bean '" + beanName + "'");117 }118 //如果不在inCreationCheckExclusions中,且可以向singletonsCurrentlyInCreation中添加,就抛出异常119 beforeSingletonCreation(beanName);120 //是否有记录被压制的异常121 boolean recordSuppressedExceptions = (this.suppressedExceptions == null);122 if (recordSuppressedExceptions) { //如果没有记录,即没有被压制的异常,就创建被压制的异常容器123 this.suppressedExceptions = new LinkedHashSet ();124 }125 try {126 singletonObject = singletonFactory.getObject();//以上都没有异常产生,那么就从指定的facgtory中取127 }128 catch (BeanCreationException ex) {129 if (recordSuppressedExceptions) {130 for (Exception suppressedException : this.suppressedExceptions) {131 ex.addRelatedCause(suppressedException);132 }133 }134 throw ex;135 }136 finally {137 if (recordSuppressedExceptions) {138 this.suppressedExceptions = null;139 }140 afterSingletonCreation(beanName);141 }142 addSingleton(beanName, singletonObject);//取成功就放进singletonObjects中143 }144 return (singletonObject != NULL_OBJECT ? singletonObject : null);145 }146 }147 148 //添加一个被压制的异常149 protected void onSuppressedException(Exception ex) {150 synchronized (this.singletonObjects) {151 if (this.suppressedExceptions != null) {152 this.suppressedExceptions.add(ex);153 }154 }155 }156 157 //根据名称移除本容器中缓存的对应的单例Bean,把对应的单例从Bean集合、单例工厂集合、早期单例对象集合、注册过的单例集合都统统移除158 protected void removeSingleton(String beanName) {159 synchronized (this.singletonObjects) {160 this.singletonObjects.remove(beanName);161 this.singletonFactories.remove(beanName);162 this.earlySingletonObjects.remove(beanName);163 this.registeredSingletons.remove(beanName);164 }165 }166 //SingletonBeanRegistry接口的实现类167 public boolean containsSingleton(String beanName) {168 return (this.singletonObjects.containsKey(beanName));169 }170 171 //SingletonBeanRegistry接口的实现类172 public String[] getSingletonNames() {173 synchronized (this.singletonObjects) {174 return StringUtils.toStringArray(this.registeredSingletons);175 }176 }177 //SingletonBeanRegistry接口的实现类178 public int getSingletonCount() {179 synchronized (this.singletonObjects) {180 return this.registeredSingletons.size();181 }182 }183 184 // 设置某个Bean是否正在创建185 public void setCurrentlyInCreation(String beanName, boolean inCreation) {186 Assert.notNull(beanName, "Bean name must not be null");187 if (!inCreation) {188 this.inCreationCheckExclusions.put(beanName, Boolean.TRUE);189 }190 else {191 this.inCreationCheckExclusions.remove(beanName);192 }193 }194 195 //判断某个Bean是否正在被创建196 public boolean isCurrentlyInCreation(String beanName) {197 Assert.notNull(beanName, "Bean name must not be null");198 return (!this.inCreationCheckExclusions.containsKey(beanName) && isActuallyInCreation(beanName));199 }200 201 protected boolean isActuallyInCreation(String beanName) {202 return isSingletonCurrentlyInCreation(beanName);203 }204 205 //是否即将被创建206 public boolean isSingletonCurrentlyInCreation(String beanName) {207 return this.singletonsCurrentlyInCreation.containsKey(beanName);208 }209 210 //单例类创建开始之前调用211 //如果不在正在创建的单例类集合中,且可以向即将创建的单例类中添加,就抛出异常212 protected void beforeSingletonCreation(String beanName) {213 if (!this.inCreationCheckExclusions.containsKey(beanName) &&214 this.singletonsCurrentlyInCreation.put(beanName, Boolean.TRUE) != null) {215 throw new BeanCurrentlyInCreationException(beanName);216 }217 }218 219 //单例类创建之后调用220 //如果不在正在创建的单例类中,也不在即将创建的单例类中移除失败,就抛出异常221 protected void afterSingletonCreation(String beanName) {222 if (!this.inCreationCheckExclusions.containsKey(beanName) &&223 !this.singletonsCurrentlyInCreation.remove(beanName)) {224 throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");225 }226 }227 228 //往Disposable实例集合注册Disposable实例229 public void registerDisposableBean(String beanName, DisposableBean bean) {230 synchronized (this.disposableBeans) {231 this.disposableBeans.put(beanName, bean);232 }233 }234 235 //注册一个被包含的Bean和一个包含它的Bean(子->父)236 public void registerContainedBean(String containedBeanName, String containingBeanName) {237 synchronized (this.containedBeanMap) {238 Set containedBeans = this.containedBeanMap.get(containingBeanName);239 if (containedBeans == null) {240 containedBeans = new LinkedHashSet (8);//containedBeans的初始容量为8241 this.containedBeanMap.put(containingBeanName, containedBeans);//注意!containedBeanMap的Key是父bean,value是其所包含的所有子Bean(父->子)242 }243 containedBeans.add(containedBeanName);244 }245 registerDependentBean(containedBeanName, containingBeanName);//因为包含也是依赖的一种,所以此时也要注册在dependentBeanMap中246 }247 248 //给指定的Bean注册一个其依赖的Bean249 public void registerDependentBean(String beanName, String dependentBeanName) {250 String canonicalName = canonicalName(beanName);//在aliasMap中取规范名251 synchronized (this.dependentBeanMap) { // 这里是注册依赖BeanMap,key是bean的名称,value是依赖这个bean的所有bean的名称252 Set dependentBeans = this.dependentBeanMap.get(canonicalName);253 if (dependentBeans == null) {254 dependentBeans = new LinkedHashSet (8);//dependentBeans的初始容量也为8255 this.dependentBeanMap.put(canonicalName, dependentBeans);//dependentBeanMap中Key为beanName的规范名,value是依赖它的所有Bean的名称256 }257 dependentBeans.add(dependentBeanName);258 }259 synchronized (this.dependenciesForBeanMap) { // 这里相反,注册的是某个Bean和其所依赖的Bean的集合,key是这个beanName,value是这个Bean的依赖的所有Bean的Name260 Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName);261 if (dependenciesForBean == null) {262 dependenciesForBean = new LinkedHashSet (8);263 this.dependenciesForBeanMap.put(dependentBeanName, dependenciesForBean);264 }265 dependenciesForBean.add(canonicalName);266 }267 }268 269 //判断某个Bean是否被其他Bean所依赖270 protected boolean hasDependentBean(String beanName) {271 return this.dependentBeanMap.containsKey(beanName);272 }273 274 //返回依赖于给定Bean的Bean名称的集合275 public String[] getDependentBeans(String beanName) {276 Set dependentBeans = this.dependentBeanMap.get(beanName);277 if (dependentBeans == null) {278 return new String[0];279 }280 return StringUtils.toStringArray(dependentBeans);281 }282 283 //返回某个Bean所依赖的所有Bean的名称284 public String[] getDependenciesForBean(String beanName) {285 Set dependenciesForBean = this.dependenciesForBeanMap.get(beanName);286 if (dependenciesForBean == null) {287 return new String[0];288 }289 return dependenciesForBean.toArray(new String[dependenciesForBean.size()]);290 }291 292 //这个方法居然连注释都没有?太奇怪了!293 public void destroySingletons() {294 if (logger.isInfoEnabled()) {295 logger.info("Destroying singletons in " + this);296 }297 synchronized (this.singletonObjects) { //首先标记,所有的单例Bean正在被销毁,那么getSingleton就无法获得单例Bean了298 this.singletonsCurrentlyInDestruction = true;299 }300 301 String[] disposableBeanNames;302 synchronized (this.disposableBeans) { //然后把所有的disposableBean都放进数组,一个个按名称销毁303 disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());304 }305 for (int i = disposableBeanNames.length - 1; i >= 0; i--) {306 destroySingleton(disposableBeanNames[i]);307 }308 // 把本容器的所有的包含关系、依赖关系、被依赖关系的集合全部清空309 this.containedBeanMap.clear();310 this.dependentBeanMap.clear();311 this.dependenciesForBeanMap.clear();312 313 //然后把本容器的所有其他集合全部清空314 synchronized (this.singletonObjects) {315 this.singletonObjects.clear();316 this.singletonFactories.clear();317 this.earlySingletonObjects.clear();318 this.registeredSingletons.clear();319 this.singletonsCurrentlyInDestruction = false;320 }321 }322 323 //销毁某个单例Bean324 public void destroySingleton(String beanName) {325 // Remove a registered singleton of the given name, if any.326 removeSingleton(beanName);//先把它销毁327 328 DisposableBean disposableBean;//它相应的DisposableBean实例329 synchronized (this.disposableBeans) {330 disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);//从disposableBeans移除这个实例331 }332 destroyBean(beanName, disposableBean);333 }334 335 // 销毁指定名称的Bean,且销毁依赖于它的所有Bean336 protected void destroyBean(String beanName, DisposableBean bean) {337 // 首先销毁依赖它的所有Bean338 Set dependencies = this.dependentBeanMap.remove(beanName);//取依赖于指定Bean的所有Bean339 if (dependencies != null) {340 if (logger.isDebugEnabled()) {341 logger.debug("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);342 }343 for (String dependentBeanName : dependencies) {344 destroySingleton(dependentBeanName);//一个个销毁345 }346 }347 348 // 然后销毁它349 if (bean != null) {350 try {351 bean.destroy();352 }353 catch (Throwable ex) {354 logger.error("Destroy method on bean with name '" + beanName + "' threw an exception", ex);355 }356 }357 358 // 然后销毁它所包含的Bean359 Set containedBeans = this.containedBeanMap.remove(beanName);360 if (containedBeans != null) {361 for (String containedBeanName : containedBeans) {362 destroySingleton(containedBeanName);363 }364 }365 366 // 然后把所有它依赖的Bean的依赖关系删除,首先删除dependentBeanMap中的依赖关系367 synchronized (this.dependentBeanMap) {368 //这样的for循环用法实在是经典369 for (Iterator >> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) {370 Map.Entry > entry = it.next();371 Set dependenciesToClean = entry.getValue();372 dependenciesToClean.remove(beanName);373 if (dependenciesToClean.isEmpty()) {374 it.remove();375 }376 }377 }378 379 // 然后删除dependenciesForBeanMap中的依赖关系380 this.dependenciesForBeanMap.remove(beanName);381 }382 383 /**384 * Expose the singleton mutex to subclasses.385 *
Subclasses should synchronize on the given Object if they perform386 * any sort of extended singleton creation phase. In particular, subclasses387 * should not have their own mutexes involved in singleton creation,388 * to avoid the potential for deadlocks in lazy-init situations.389 */390 //返回子类单例类的互斥体?这个暂且放着。391 protected final Object getSingletonMutex() {392 return this.singletonObjects;393 }394 395 }
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.springframework.beans.factory.support;import java.security.AccessControlContext;import java.security.AccessController;import java.security.PrivilegedAction;import java.security.PrivilegedActionException;import java.security.PrivilegedExceptionAction;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import org.springframework.beans.BeansException;import org.springframework.beans.factory.BeanCreationException;import org.springframework.beans.factory.BeanCurrentlyInCreationException;import org.springframework.beans.factory.FactoryBean;import org.springframework.beans.factory.FactoryBeanNotInitializedException;/** * Support base class for singleton registries which need to handle * { @link org.springframework.beans.factory.FactoryBean} instances, * integrated with { @link DefaultSingletonBeanRegistry}'s singleton management. * *
Serves as base class for {
@link AbstractBeanFactory}. * * @author Juergen Hoeller * @since 2.5.1 */public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry { /** 工厂Bean生产的单例的集合: FactoryBean name --> object */ private final Map factoryBeanObjectCache = new ConcurrentHashMap (16); //返回指定FactoryBean的类型 protected Class getTypeForFactoryBean(final FactoryBean factoryBean) { try { if (System.getSecurityManager() != null) { //如果当前系统存在安全管理器 return AccessController.doPrivileged(new PrivilegedAction () { //那么返回factoryBean的类型这个操作不做权限检查,直接调用 public Class run() { return factoryBean.getObjectType(); } }, getAccessControlContext()); } else { //不存在安全管理器,就直接调用! return factoryBean.getObjectType(); } } catch (Throwable ex) { logger.warn("FactoryBean threw exception from getObjectType, despite the contract saying " + "that it should return null if the type of its object cannot be determined yet", ex); return null; } } //根据FactoryBean名,返回其生产的Object,从缓存中取 protected Object getCachedObjectForFactoryBean(String beanName) { Object object = this.factoryBeanObjectCache.get(beanName); return (object != NULL_OBJECT ? object : null); } //从工厂Bean中取实例,实际调用下面的doGetObjectFromFactoryBean方法。 protected Object getObjectFromFactoryBean(FactoryBean factory, String beanName, boolean shouldPostProcess) { if (factory.isSingleton() && containsSingleton(beanName)) { //若工厂是单例,且本容器包含beanName对应的单例类 synchronized (getSingletonMutex()) { //以所有的单例集合为锁 Object object = this.factoryBeanObjectCache.get(beanName);//根据beanName从factoryBeanObjectCache中取 if (object == null) { //若取不到 object = doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess); this.factoryBeanObjectCache.put(beanName, (object != null ? object : NULL_OBJECT));//放进factoryBeanObjectCache } return (object != NULL_OBJECT ? object : null); } } else { //否则,直接 return doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess); } } //从工厂Bean中取实例 private Object doGetObjectFromFactoryBean( final FactoryBean factory, final String beanName, final boolean shouldPostProcess) throws BeanCreationException { Object object; //跟getTypeForFactoryBean的实现一样。 try { if (System.getSecurityManager() != null) { //若系统存在安全管理器 AccessControlContext acc = getAccessControlContext();//得到当前容器的安全访问上下文 try { //返回factoryBean的类型这个操作不做权限检查,直接调用 object = AccessController.doPrivileged(new PrivilegedExceptionAction
View Code
具体:
1、1个不可变的实例属性ConcurrentHashMap来存放工厂Bean生产的单例的集合:FactoryBean name --> object。
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory { //父工厂的引用 private BeanFactory parentBeanFactory; //类加载器 private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); //临时类加载器 private ClassLoader tempClassLoader; /** Whether to cache bean metadata or rather reobtain it for every access */ private boolean cacheBeanMetadata = true; //Bean表达式分解器,用来分解Bean定义中的表达式 private BeanExpressionResolver beanExpressionResolver; //转换服务,用来替代属性编辑器的 private ConversionService conversionService; //属性编辑登记员集合,容量为4的LinkedHashSet private final Set propertyEditorRegistrars = new LinkedHashSet (4); //通用的类型转换器,重写了默认的属相编辑器机制 private TypeConverter typeConverter; //默认的属性编辑器集合 private final Map , Class > customEditors = new HashMap , Class >(4); //嵌入值转换器集合 private final List embeddedValueResolvers = new LinkedList (); //BeanPostProcessor处理器集合 private final List beanPostProcessors = new ArrayList (); //标记是否有InstantiationAwareBeanPostProcessors实例被注册 private boolean hasInstantiationAwareBeanPostProcessors; //标记是否有DestructionAwareBeanPostProcessors实例被注册 private boolean hasDestructionAwareBeanPostProcessors; //范围标识符和Scope实例的对应的Map private final Map scopes = new HashMap (8); //安全上下文Provider,可以得到安全管理器的安全上下文 private SecurityContextProvider securityContextProvider; //合并后的Bean根定义的集合 private final Map mergedBeanDefinitions = new ConcurrentHashMap (64); //至少被创建过一次的Bean的集合 private final Map alreadyCreated = new ConcurrentHashMap (64); //当前正在创建的原型,当前线程相关 private final ThreadLocal