博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring 之 BeanFactory 源码 - 抽象/类 分析
阅读量:4925 次
发布时间:2019-06-11

本文共 85524 字,大约阅读时间需要 285 分钟。

BeanFactory的基本类体系结构(类为主):

  上图可与  的图结合分析,一个以接口为主,一个以类为主

具体:

  1、7层的类体系继承。

  2、AbstractBeanFactory实现了最重要的ConfigurableBeanFactory接口,DefaultSingletonBeanRegistry实现了SingletonBeanRegistry单例类注册接口,SimpleAliasRegistry实现了AliasRegistry别名注册接口。

  3、祖先类SimpleAliasRegistry、DefaultSingletonBeanRegistry和子孙类XmlBeanFactory、DefaultListableBeanFactory是完整的类,而中间的类FactoryBeanRegistrySupport、AbstractBeanFactory、AbstractAutowireCapableBeanFactory都是抽象类。

总结:

  具体上来说,XmlBeanFactory光是父类就有6个了,加上自身,总共7层了。实际上分析接口结构就会看到,作为IOC类工厂而言,XmlBeanFactory的类体系结构实际是从祖先AbstractBeanFactory这个类开始的,因为是它实现了BeanFactory的子接口ConfigurableBeanFactory,虽然它继承自FactoryBeanRegistrySupport,但可以说这只是工厂功能的扩充,扩展了对工厂Bean以及工厂所产生的Bean的操作。

 

简单的别名注册器——SimpleAliasRegistry

  上篇已经讲过AliasRegistry,非常简单的4个方法,体现了对别名注册的支持,而SimpleAliasRegistry就是它的简单实现。

源码:

1 public class SimpleAliasRegistry implements AliasRegistry {  2   3     /*  4      *用一个支持高并发的ConcurrentHashMap来放置所有的别名  5      */  6     private final Map
aliasMap = new ConcurrentHashMap
( 7 16); 8 9 // AliasRegistry的接口方法,注册别名。不允许重复注册。 10 public void registerAlias(String name, String alias) { 11 Assert.hasText(name, "'name' must not be empty"); 12 Assert.hasText(alias, "'alias' must not be empty"); 13 if (alias.equals(name)) { 14 this.aliasMap.remove(alias); 15 } else { 16 if (!allowAliasOverriding()) { 17 String registeredName = this.aliasMap.get(alias); 18 if (registeredName != null && !registeredName.equals(name)) { 19 throw new IllegalStateException("Cannot register alias '" 20 + alias + "' for name '" + name 21 + "': It is already registered for name '" 22 + registeredName + "'."); 23 } 24 } 25 checkForAliasCircle(name, alias);//alias不能等于name在map中最后的对应(详见checkForAliasCircle方法) 26 this.aliasMap.put(alias, name);//alias是key,name是value 27 } 28 } 29 30 /** 31 * 返回是否允许Alias重写,默认为允许 32 */ 33 protected boolean allowAliasOverriding() { 34 return true; 35 } 36 37 // AliasRegistry的接口方法,移除别名,如果别名未注册,则抛出异常 38 public void removeAlias(String alias) { 39 String name = this.aliasMap.remove(alias); 40 if (name == null) { 41 throw new IllegalStateException("No alias '" + alias 42 + "' registered"); 43 } 44 } 45 46 // AliasRegistry的接口方法,给定名称判断是否为别名 47 public boolean isAlias(String name) { 48 return this.aliasMap.containsKey(name); 49 } 50 51 // AliasRegistry的接口方法 52 public String[] getAliases(String name) { 53 List
result = new ArrayList
(); 54 synchronized (this.aliasMap) { 55 retrieveAliases(name, result); 56 } 57 return StringUtils.toStringArray(result); 58 } 59 60 /* 61 * 找出名字说对应的所有别名。 62 */ 63 private void retrieveAliases(String name, List
result) { 64 for (Map.Entry
entry : this.aliasMap.entrySet()) { //遍历aliasMap 65 String registeredName = entry.getValue();//取aliasMap的每个value 66 if (registeredName.equals(name)) { //如果value等于指定的这个name 67 String alias = entry.getKey();//取value对应的key 68 result.add(alias);//将alias加入 69 retrieveAliases(alias, result);//继续查看以alias为value的key 70 } 71 } 72 } 73 74 /* 75 * 处理所有的别名,如果处理正确,把原来的用解析后的替换 76 */ 77 public void resolveAliases(StringValueResolver valueResolver) { 78 Assert.notNull(valueResolver, "StringValueResolver must not be null"); 79 synchronized (this.aliasMap) { 80 Map
aliasCopy = new HashMap
( 81 this.aliasMap); 82 for (String alias : aliasCopy.keySet()) { 83 String registeredName = aliasCopy.get(alias);//取出key对应的value 84 String resolvedAlias = valueResolver.resolveStringValue(alias);//解析后的key 85 String resolvedName = valueResolver 86 .resolveStringValue(registeredName);//解析后的value 87 if (resolvedAlias.equals(resolvedName)) { //若解析后的key、name相等,就把它们从aliasMap中移除 88 this.aliasMap.remove(alias); 89 } else if (!resolvedAlias.equals(alias)) { //若解析后的key不等于原来的Key 90 String existingName = this.aliasMap.get(resolvedAlias);//取出解析后的key对应的value 91 if (existingName != null//如果不为空且不等于解析后的value,就抛出异常 92 && !existingName.equals(resolvedName)) { 93 throw new IllegalStateException( 94 "Cannot register resolved alias '" 95 + resolvedAlias 96 + "' (original: '" 97 + alias 98 + "') for name '" 99 + resolvedName100 + "': It is already registered for name '"101 + registeredName + "'.");102 }103 checkForAliasCircle(resolvedName, resolvedAlias);104 this.aliasMap.remove(alias);105 this.aliasMap.put(resolvedAlias, resolvedName);106 } else if (!registeredName.equals(resolvedName)) {107 this.aliasMap.put(alias, resolvedName);108 }109 }110 }111 }112 113 /*114 * 根据name这个Key,在aliasMap中不断循环的取对应的value,如果取得到,就继续根据这个value取值,不断循环继续。115 * 直到取不到,就把这个在aliasMap中无对应值的key返回。116 */117 public String canonicalName(String name) {118 String canonicalName = name; //规范名119 // Handle aliasing...120 String resolvedName;//已解析名121 do {122 resolvedName = this.aliasMap.get(canonicalName);//aliasMap中规范名对应的值赋值给已解析名123 if (resolvedName != null) { //如果已解析名存在(即规范名在aliasMap中有对应的值)124 canonicalName = resolvedName; // 这个已解析名赋值给标准名125 }126 } while (resolvedName != null);//不断循环,直到已解析名不存在127 return canonicalName;128 }129 130 /*131 * 如果别名alias等于canonicalName(name)就抛出异常132 */133 protected void checkForAliasCircle(String name, String alias) {134 if (alias.equals(canonicalName(name))) {135 throw new IllegalStateException("Cannot register alias '" + alias136 + "' for name '" + name + "': Circular reference - '"137 + name + "' is a direct or indirect alias for '" + alias138 + "' already");139 }140 }141 142 }
View Code

 

 具体:

  1、1个支持高并发的ConcurrentHashMap来放置所有的别名,其中key是别名,value是真名。

  2、4个方法实现了SimpleAliasRegistry。

  3、3个用来辅助实现4个接口方法的方法。其中canonicalName(String name)的实现非常优雅,用来循环来回判断,把aliasMap中无对应值的key返回。

  4、2个添加额外功能的方法 retrieveAliases 和 resolveAliases ,前者是找出名字对应的所有别名,后者是用一个StringValueResolver处理解析所有的别名-名称。

总结:

  这是一个非常简单的别名注册器,一个简单的接口实现。不过其中包含了非常优雅的方法实现,值得一看!

 

默认单例注册类——DefaultSingletonBeanRegistry

源码:   

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 }

View Code

 

 

具体:

  1、一个静态不可变的空对象NULL_OBJECT、一个简单的日志对象。

  2、本类有如下集合:

    (1)、一个单例缓存集合——singletonObjects

    (2)、一个单例工厂缓存集合——singletonFactories

    (3)、一个早期单例对象缓存集合——earlySingletonObjects

    (4)、一个注册过的单例类(单例工厂)集合——registeredSingletons

    (5)、一个即将创建的单例类集合——singletonsCurrentlyInCreation

    (6)、一个正在创建的单例类集合——inCreationCheckExclusions

    (7)、一个被压制的异常集合——suppressedExceptions(这种设计模式实在是经典!)

    (8)、一个判断所有单例类是否马上被销毁的标记——singletonsCurrentlyInDestruction

    (9)、一个Disposable接口(即可以自定义回收资源的接口)实例的集合——disposableBeans

    (10)、一个bean名称和bean所有包含的Bean的名称的集合——containedBeanMap

    (11)、bean名称和所有依赖于Bean的名称的集合——dependentBeanMap

    (12)、bean名称和bean所依赖的所有名称的集合——dependenciesForBeanMap

  3、2个注册单例方法,实际是暴露在外的SingletonBeanRegistry接口的实现方法registerSingleton加锁后调用另一个addSingleton方法。

  4、1个注册单例工厂的方法。单例工厂类不能和单例类同名。

  5、3个获取单例类的方法。一种是从单例类集合中获取,如果获取不到,boolean控制要么返回空对象,要么返回一个单例工厂。另一种是从单例集合中获取,如果取不到,就从指定的工厂中获取。还有一种?呵,就是暴露在外的SingletonBeanRegistry接口方法呗,直接调用第一种。

  6、1个添加被压制的异常集合中添加异常的方法,我觉得这个设计非常经典。但需要记录异常,却不想处理的时候,可以采用这种设计模式。

  7、1个移除单例的方法、1个判断是否包含单例的方法、1个返回所有单例名数组的方法、1个返回单例总数目的方法。

  8、1个设置某个Bean是否正在创建的方法、1个判断某个Bean是否正在被创建的方法、2个判断某个Bean是否即将被创建的方法(一个调用另一个,用于重写)。

  9、1个单例类创建开始之前调用的方法、1个单单例类创建之后调用的方法

  10、1个往Disposable实例集合注册Disposable实例的方法,这个是Bean销毁前的准备。

  11、1个注册一个被包含的Bean和一个包含的Bean的名称到containedBeanMap集合的方法。这个方法设置了Bean之间的包含关系。

  12、1个给指定的Bean注册一个其依赖的Bean的方法。这个方法设置了Bean自己的依赖关系。

  13、1个判断是否被依赖的方法、1个返回给定Bean名称的所有依赖的数组的方法、1个返回依赖于给定Bean的所有Bean名的数组的方法。

  14、1个销毁所有单例类的方法(这个方法居然完全没有注释,有没搞错!)、1个销毁某个单例的方法、1个// 销毁指定名称的Bean,且销毁依赖于它的所有Bean的方法。

  15、1个返回子类单例类的互斥体的方法。这个暂且待下一篇分析子类再看。

总结:

  类如其名,默认的单例注册器。这个工厂的写法实在功能丰富,为了监控到一个单例类构建过程中的方方面面,简直就是不择手段啊,居然准备了12个集合,除了一个一个被压制的异常集合,其余全是跟单例类有直接关系的。可以说,这个单例注册器监听、实现了Spring单例注册的各个过程,具体的解读分析,在上面的源代码中可以看到,读者阅读我注释过的源代码应该会很轻松。

 

 

工厂Bean注册支持——FactoryBeanRegistrySupport

废话不多说,直接看我注释的源码:

/* * 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
() { public Object run() throws Exception { return factory.getObject(); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else {
//否则直接取 object = factory.getObject(); } } catch (FactoryBeanNotInitializedException ex) { throw new BeanCurrentlyInCreationException(beanName, ex.toString()); } catch (Throwable ex) { throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex); } //如果从beanFactory取不到,且这个实例即将被创建,抛出异常 if (object == null && isSingletonCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException( beanName, "FactoryBean which is currently in creation returned null from getObject"); } //若取不到,且这个实例允许前处理 if (object != null && shouldPostProcess) { try { object = postProcessObjectFromFactoryBean(object, beanName);//这里简单返回,前处理的功能留给子类重写 } catch (Throwable ex) { throw new BeanCreationException(beanName, "Post-processing of the FactoryBean's object failed", ex); } } return object; } //这里简单返回Object,留给子类重写 protected Object postProcessObjectFromFactoryBean(Object object, String beanName) throws BeansException { return object; } //如果这个Object是FactoryBean类型,就转换成FactoryBean返回 protected FactoryBean getFactoryBean(String beanName, Object beanInstance) throws BeansException { if (!(beanInstance instanceof FactoryBean)) { throw new BeanCreationException(beanName, "Bean instance of type [" + beanInstance.getClass() + "] is not a FactoryBean"); } return (FactoryBean) beanInstance; } //移除单例类这个方法重写,父类的移除之外,还要移除factoryBeanObjectCache中的。 @Override protected void removeSingleton(String beanName) { super.removeSingleton(beanName); this.factoryBeanObjectCache.remove(beanName); } //返回当前容器的安全访问上下文 protected AccessControlContext getAccessControlContext() { return AccessController.getContext(); }}

View Code

 

具体:

  1、1个不可变的实例属性ConcurrentHashMap来存放工厂Bean生产的单例的集合:FactoryBean name --> object。

  2、1个方法返回指定FactoryBean的类型的方法。

  3、1个根据FactoryBean名,返回其生产的Object的方法。

  4、2个从工厂Bean中取实例的方法。实际是一个方法调用另一个,取不到则返回空。

  5、1个postProcessObjectFromFactoryBean的方法,留给子类重写。

  6、1个取工厂Bean的方法——如果这个Object是FactoryBean类型,就转换成FactoryBean返回

  7、1个重写父类的removeSingleton方法,移除单例的时候,父类的移除之外,还要移除factoryBeanObjectCache中的。

  8、1个返回当前容器的安全访问上下文的方法。

总结:

  这个类FactoryBeanRegistrySupport,类如其名,实现了对工厂Bean注册的支持。值得注意的是,这个类有较多类似如下的写法:

if (System.getSecurityManager() != null) {//如果当前系统存在安全管理器                return AccessController.doPrivileged(new PrivilegedAction
() { public Class run() { //实际处理 } }, getAccessControlContext()); } else {//不存在安全管理器,就直接调用! //实际处理 }

   

  这个方法的意思是,如果当前系统存在安全管理器,那么接下来的操作不做权限检查,直接调用。而如果不存在,OK,那当然是直接调用了。这是JDK层面的一个系统安全管理工具,某些情况下,可以避免系统进行安全检查。这里稍作了解即可。在学习JVM的时候可仔细了解原理。

  除此之外,这里可以了解一下这个类比较重要的方法doGetObjectFromFactoryBean,是从工厂Bean中取实例的方法,源码已经给出,这里重点指出一下,不必折叠了:

//从工厂Bean中取实例,shouldPostProcess指的是是否允许提前处理    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() {                        public Object run() throws Exception {                                return factory.getObject();                            }                        }, acc);                }                catch (PrivilegedActionException pae) {                    throw pae.getException();                }            }            else {//否则直接取                object = factory.getObject();            }        }        catch (FactoryBeanNotInitializedException ex) {            throw new BeanCurrentlyInCreationException(beanName, ex.toString());        }        catch (Throwable ex) {            throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);        }        //如果从beanFactory取不到,且这个实例即将被创建,抛出异常        if (object == null && isSingletonCurrentlyInCreation(beanName)) {            throw new BeanCurrentlyInCreationException(                    beanName, "FactoryBean which is currently in creation returned null from getObject");        }        //若取不到,并非即将创建、且这个实例允许前处理        if (object != null && shouldPostProcess) {            try {                object = postProcessObjectFromFactoryBean(object, beanName);//这里简单返回,前处理的功能留给子类重写            }            catch (Throwable ex) {                throw new BeanCreationException(beanName, "Post-processing of the FactoryBean's object failed", ex);            }        }        return object;    }

   

  相信上面已经解释的很清楚了。

 

最重要的抽象类——AbstractBeanFactory

  (PS:这个类的方法实在是多的骇人,看得我实在是头都大了。不多看到后面,发现很多方法其实也就是那么回事。源码注释了大部分,且看看咯!)

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
prototypesCurrentlyInCreation = new NamedThreadLocal("Prototype beans currently in creation"); //空构造方法 public AbstractBeanFactory() { } //指定父Bean工厂的构造方法 public AbstractBeanFactory(BeanFactory parentBeanFactory) { this.parentBeanFactory = parentBeanFactory; } //--------------------------------------------------------------------- // 3个getBean,BeanFactory接口的实现方法,实质是在调用doGetBean //--------------------------------------------------------------------- public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); } public
T getBean(String name, Class
requiredType) throws BeansException { return doGetBean(name, requiredType, null, false); } public Object getBean(String name, Object... args) throws BeansException { return doGetBean(name, null, args, false); } // 提供创建时需要参数列表的getBean public
T getBean(String name, Class
requiredType, Object... args) throws BeansException { return doGetBean(name, requiredType, args, false); } //从容器中获取bean的基本方法。 @SuppressWarnings("unchecked") protected
T doGetBean( final String name, final Class
requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name);//在aliasMap中取得的标准名 Object bean; // Eagerly check singleton cache for manually registered singletons. Object sharedInstance = getSingleton(beanName);//首先在单例集合中取 if (sharedInstance != null && args == null) { //如果取得到,没有指定参数 if (logger.isDebugEnabled()) { //若Log允许调试 if (isSingletonCurrentlyInCreation(beanName)) { //若正准备创建,输出日志 logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); } } 根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { if (isPrototypeCurrentlyInCreation(beanName)) { //如果正在被创建,就抛出异常 throw new BeanCurrentlyInCreationException(beanName); } BeanFactory parentBeanFactory = getParentBeanFactory();//取本容器的父容器 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { //若存在父容器,且本容器不存在对应的Bean定义 String nameToLookup = originalBeanName(name);//取原始的Bean名 if (args != null) { //若参数列表存在 // 那么用父容器根据原始Bean名和参数列表返回 return (T) parentBeanFactory.getBean(nameToLookup, args); } else { // 参数列表不要求,那就直接根据原始名称和要求的类型返回 return parentBeanFactory.getBean(nameToLookup, requiredType); } } //如果不需要类型检查,标记其已经被创建 if (!typeCheckOnly) { markBeanAsCreated(beanName); } //根据beanName取其根Bean定义 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); String[] dependsOn = mbd.getDependsOn();//得到这个根定义的所有依赖 if (dependsOn != null) { for (String dependsOnBean : dependsOn) { getBean(dependsOnBean);//注册这个Bean //注册一个Bean和依赖于它的Bean(后参数依赖前参数) registerDependentBean(dependsOnBean, beanName); } } // 如果Bean定义是单例,就在返回单例 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, new ObjectFactory
() { public Object getObject() throws BeansException { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { destroySingleton(beanName); throw ex; } } }); //根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } //如果是原型 else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName);//原型创建前,与当前线程绑定 prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName);//原型创建后,与当前线程解除绑定 } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { //既不是单例又不是原型的情况 String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName);//得到范围 if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'"); } try { //根据范围创建实例 Object scopedInstance = scope.get(beanName, new ObjectFactory() { public Object getObject() throws BeansException { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args);//原型创建前,与当前线程绑定 } finally { 原型创建后,与当前线程解除绑定 afterPrototypeCreation(beanName); } } }); //根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; " + "consider defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } } } //判断要求的类型是否和Bean实例的类型正在匹配 if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { try { return getTypeConverter().convertIfNecessary(bean, requiredType);//转换类型,不抛出异常就说明类型匹配 } catch (TypeMismatchException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to convert bean '" + name + "' to required type [" + ClassUtils.getQualifiedName(requiredType) + "]", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; } //判断本容器是否包含指定bean public boolean containsBean(String name) { String beanName = transformedBeanName(name); // (如果是否包含单例 或 包含Bean定义)且 (为工厂Bean的产物 或 本身就是工厂bean),就返回true if (containsSingleton(beanName) || containsBeanDefinition(beanName)) { return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name)); } // 如果不包含单例且不包含Bean定义,就从父类去查找 BeanFactory parentBeanFactory = getParentBeanFactory(); return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name))); } //判断指定Bean是否为单例 public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); Object beanInstance = getSingleton(beanName, false);//首先从单例集合中取 if (beanInstance != null) { //取不到,就判断它是不是FactoryBean的实例 if (beanInstance instanceof FactoryBean) { // 如果是,要求它是工厂Bean产生的实例或这个工厂bean是单例 return (BeanFactoryUtils.isFactoryDereference(name) || ((FactoryBean
) beanInstance).isSingleton()); } else { // 如果不是,要求它不是工厂Bean产生的实例 return !BeanFactoryUtils.isFactoryDereference(name); } }//若虽然取不到,但是单例集合中包含它的名字,说明它是单例 else if (containsSingleton(beanName)) { return true; } else { //从父工厂中去查询Bean定义 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { //父工厂找不到Bean定义,那就在父工厂根据原始名去查是否为单例 return parentBeanFactory.isSingleton(originalBeanName(name)); } //返回一个合并后的根Bean定义 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // In case of FactoryBean, return singleton status of created object if not a dereference. //若该根定义是单例 if (mbd.isSingleton()) { if (isFactoryBean(beanName, mbd)) { //若该根定义为工厂Bean if (BeanFactoryUtils.isFactoryDereference(name)) { //判断是否为工厂产生的实例 return true; } //取对应的工厂,判断该工厂Bean是否为单例 FactoryBean
factoryBean = (FactoryBean
) getBean(FACTORY_BEAN_PREFIX + beanName); return factoryBean.isSingleton(); } else { // 是否不为工厂Bean产生的实例(此时,即,该根定义不为工厂Bean,且不为工厂Bean产生的实例的时候,由于根定义是单例,那么它就是单例) return !BeanFactoryUtils.isFactoryDereference(name); } } else { return false; } } } //判断是否为原型 public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); BeanFactory parentBeanFactory = getParentBeanFactory();//得到父工厂 //若父工厂中的定义为原型,就为原型 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { return parentBeanFactory.isPrototype(originalBeanName(name)); } //若合并后的根定义为原型,且不是工厂Bean产生的实例、或本身是工厂Bean,那么就为原型 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); if (mbd.isPrototype()) { return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd)); } else { if (BeanFactoryUtils.isFactoryDereference(name)) { //若为工厂Bean产生的实例 return false; } if (isFactoryBean(beanName, mbd)) { //若为工厂Bean,取它产生的Bean,判断SmartFactoryBean final FactoryBean
factoryBean = (FactoryBean
) getBean(FACTORY_BEAN_PREFIX + beanName); if (System.getSecurityManager() != null) { return AccessController.doPrivileged(new PrivilegedAction
() { public Boolean run() { return ((factoryBean instanceof SmartFactoryBean && ((SmartFactoryBean
) factoryBean).isPrototype()) || !factoryBean.isSingleton()); } }, getAccessControlContext()); } else { return ((factoryBean instanceof SmartFactoryBean && ((SmartFactoryBean
) factoryBean).isPrototype()) || !factoryBean.isSingleton()); } } else { return false; } } } //判断类型是否匹配 public boolean isTypeMatch(String name, Class
targetType) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); Class
typeToMatch = (targetType != null ? targetType : Object.class); Object beanInstance = getSingleton(beanName, false);//取name对应的单例 if (beanInstance != null) { if (beanInstance instanceof FactoryBean) { //若为工厂Bean //若不是工厂Bean产生的实例 if (!BeanFactoryUtils.isFactoryDereference(name)) { //取工厂Bean的类型与targetType进行对比 Class
type = getTypeForFactoryBean((FactoryBean
) beanInstance); return (type != null && ClassUtils.isAssignable(typeToMatch, type)); } else { return ClassUtils.isAssignableValue(typeToMatch, beanInstance); } } //不是工厂Bean,那就直接判断 else { return !BeanFactoryUtils.isFactoryDereference(name) && ClassUtils.isAssignableValue(typeToMatch, beanInstance); } } //单例表中,对应的Key没有值,也不包含Bean定义,说明没有注册,返回false else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) { return false; } //以下是包含Bean定义的情况 else { //先查父类的Bean定义 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.isTypeMatch(originalBeanName(name), targetType); } //直接查合并后的根定义 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); //构建类型数组 Class[] typesToMatch = (FactoryBean.class.equals(typeToMatch) ? new Class[] {typeToMatch} : new Class[] {FactoryBean.class, typeToMatch}); // Check decorated bean definition, if any: We assume it'll be easier // to determine the decorated bean's type than the proxy's type. //得到Bean定义的持有者 BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) { //若为Bean工厂生成的实例,先得到根定义 RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd); Class
targetClass = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);//得到预测的根定义 if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return typeToMatch.isAssignableFrom(targetClass); } } Class
beanType = predictBeanType(beanName, mbd, typesToMatch);//预测后的类型 if (beanType == null) { return false; } if (FactoryBean.class.isAssignableFrom(beanType)) { //BeanFactory是否为其子类 if (!BeanFactoryUtils.isFactoryDereference(name)) { //若不为工厂Bean的产物 // If it's a FactoryBean, we want to look at what it creates, not the factory class. beanType = getTypeForFactoryBean(beanName, mbd); if (beanType == null) { return false; } } } else if (BeanFactoryUtils.isFactoryDereference(name)) { //若为工厂类Bean的产物 beanType = predictBeanType(beanName, mbd, FactoryBean.class);//预测类型 if (beanType == null || !FactoryBean.class.isAssignableFrom(beanType)) { return false; } } return typeToMatch.isAssignableFrom(beanType); } } //返回类型 public Class
getType(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); // Check manually registered singletons. Object beanInstance = getSingleton(beanName, false); if (beanInstance != null) { if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { return getTypeForFactoryBean((FactoryBean
) beanInstance); } else { return beanInstance.getClass(); } } else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) { // null instance registered return null; } else { // No singleton instance found -> check bean definition. BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.getType(originalBeanName(name)); } RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // Check decorated bean definition, if any: We assume it'll be easier // to determine the decorated bean's type than the proxy's type. BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) { RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd); Class
targetClass = predictBeanType(dbd.getBeanName(), tbd); if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return targetClass; } } Class
beanClass = predictBeanType(beanName, mbd); // Check bean class whether we're dealing with a FactoryBean. if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) { if (!BeanFactoryUtils.isFactoryDereference(name)) { // If it's a FactoryBean, we want to look at what it creates, not at the factory class. return getTypeForFactoryBean(beanName, mbd); } else { return beanClass; } } else { return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null); } } } //重写了,得到别名的方法。 @Override public String[] getAliases(String name) { String beanName = transformedBeanName(name); List
aliases = new ArrayList
(); boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX); String fullBeanName = beanName; if (factoryPrefix) { fullBeanName = FACTORY_BEAN_PREFIX + beanName; } if (!fullBeanName.equals(name)) { aliases.add(fullBeanName); } String[] retrievedAliases = super.getAliases(beanName); for (String retrievedAlias : retrievedAliases) { String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") + retrievedAlias; if (!alias.equals(name)) { aliases.add(alias); } } if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) { BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null) { aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName))); } } return StringUtils.toStringArray(aliases); } //--------------------------------------------------------------------- // Implementation of HierarchicalBeanFactory interface //--------------------------------------------------------------------- //返回本Bean工厂的父Bean工厂 public BeanFactory getParentBeanFactory() { return this.parentBeanFactory; } //是否在本容器中(就是说,并不是工厂bean生产出来的) public boolean containsLocalBean(String name) { String beanName = transformedBeanName(name); // 转换后的名字 //(是否为单例或有对应的Bean定义) 且(不是工厂Bean生产出来的 或 本身就是工厂bean) return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) && (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName))); } //--------------------------------------------------------------------- // Implementation of ConfigurableBeanFactory interface //--------------------------------------------------------------------- public void setParentBeanFactory(BeanFactory parentBeanFactory) { if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) { throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory); } this.parentBeanFactory = parentBeanFactory; } public void setBeanClassLoader(ClassLoader beanClassLoader) { this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader()); } public ClassLoader getBeanClassLoader() { return this.beanClassLoader; } public void setTempClassLoader(ClassLoader tempClassLoader) { this.tempClassLoader = tempClassLoader; } public ClassLoader getTempClassLoader() { return this.tempClassLoader; } public void setCacheBeanMetadata(boolean cacheBeanMetadata) { this.cacheBeanMetadata = cacheBeanMetadata; } public boolean isCacheBeanMetadata() { return this.cacheBeanMetadata; } public void setBeanExpressionResolver(BeanExpressionResolver resolver) { this.beanExpressionResolver = resolver; } public BeanExpressionResolver getBeanExpressionResolver() { return this.beanExpressionResolver; } public void setConversionService(ConversionService conversionService) { this.conversionService = conversionService; } public ConversionService getConversionService() { return this.conversionService; } public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) { Assert.notNull(registrar, "PropertyEditorRegistrar must not be null"); this.propertyEditorRegistrars.add(registrar); } /** * Return the set of PropertyEditorRegistrars. */ public Set
getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } public void registerCustomEditor(Class
requiredType, Class
propertyEditorClass) { Assert.notNull(requiredType, "Required type must not be null"); Assert.isAssignable(PropertyEditor.class, propertyEditorClass); this.customEditors.put(requiredType, propertyEditorClass); } public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) { registerCustomEditors(registry); } /** * Return the map of custom editors, with Classes as keys and PropertyEditor classes as values. */ public Map
, Class
> getCustomEditors() { return this.customEditors; } public void setTypeConverter(TypeConverter typeConverter) { this.typeConverter = typeConverter; } //得到通用的类型转换器 protected TypeConverter getCustomTypeConverter() { return this.typeConverter; } //得到类型转换器 public TypeConverter getTypeConverter() { TypeConverter customConverter = getCustomTypeConverter(); if (customConverter != null) { return customConverter; } else { //若本容器未注册类型转换器,就创建一个简单的类型转换器 SimpleTypeConverter typeConverter = new SimpleTypeConverter(); typeConverter.setConversionService(getConversionService()); registerCustomEditors(typeConverter); return typeConverter; } } public void addEmbeddedValueResolver(StringValueResolver valueResolver) { Assert.notNull(valueResolver, "StringValueResolver must not be null"); this.embeddedValueResolvers.add(valueResolver); } public String resolveEmbeddedValue(String value) { String result = value; for (StringValueResolver resolver : this.embeddedValueResolvers) { if (result == null) { return null; } result = resolver.resolveStringValue(result); } return result; } public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) { Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null"); this.beanPostProcessors.remove(beanPostProcessor); this.beanPostProcessors.add(beanPostProcessor); if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) { this.hasInstantiationAwareBeanPostProcessors = true; } if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) { this.hasDestructionAwareBeanPostProcessors = true; } } public int getBeanPostProcessorCount() { return this.beanPostProcessors.size(); } /** * Return the list of BeanPostProcessors that will get applied * to beans created with this factory. */ public List
getBeanPostProcessors() { return this.beanPostProcessors; } /** * Return whether this factory holds a InstantiationAwareBeanPostProcessor * that will get applied to singleton beans on shutdown. * @see #addBeanPostProcessor * @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor */ protected boolean hasInstantiationAwareBeanPostProcessors() { return this.hasInstantiationAwareBeanPostProcessors; } /** * Return whether this factory holds a DestructionAwareBeanPostProcessor * that will get applied to singleton beans on shutdown. * @see #addBeanPostProcessor * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor */ protected boolean hasDestructionAwareBeanPostProcessors() { return this.hasDestructionAwareBeanPostProcessors; } public void registerScope(String scopeName, Scope scope) { Assert.notNull(scopeName, "Scope identifier must not be null"); Assert.notNull(scope, "Scope must not be null"); if (SCOPE_SINGLETON.equals(scopeName) || SCOPE_PROTOTYPE.equals(scopeName)) { throw new IllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'"); } this.scopes.put(scopeName, scope); } public String[] getRegisteredScopeNames() { return StringUtils.toStringArray(this.scopes.keySet()); } public Scope getRegisteredScope(String scopeName) { Assert.notNull(scopeName, "Scope identifier must not be null"); return this.scopes.get(scopeName); } /** * Set the security context provider for this bean factory. If a security manager * is set, interaction with the user code will be executed using the privileged * of the provided security context. */ public void setSecurityContextProvider(SecurityContextProvider securityProvider) { this.securityContextProvider = securityProvider; } /** * Delegate the creation of the access control context to the * { @link #setSecurityContextProvider SecurityContextProvider}. */ @Override public AccessControlContext getAccessControlContext() { return (this.securityContextProvider != null ? this.securityContextProvider.getAccessControlContext() : AccessController.getContext()); } public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { Assert.notNull(otherFactory, "BeanFactory must not be null"); setBeanClassLoader(otherFactory.getBeanClassLoader()); setCacheBeanMetadata(otherFactory.isCacheBeanMetadata()); setBeanExpressionResolver(otherFactory.getBeanExpressionResolver()); if (otherFactory instanceof AbstractBeanFactory) { AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory; this.customEditors.putAll(otherAbstractFactory.customEditors); this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars); this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors); this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors || otherAbstractFactory.hasInstantiationAwareBeanPostProcessors; this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors || otherAbstractFactory.hasDestructionAwareBeanPostProcessors; this.scopes.putAll(otherAbstractFactory.scopes); this.securityContextProvider = otherAbstractFactory.securityContextProvider; } else { setTypeConverter(otherFactory.getTypeConverter()); } } //返回合并后的bean定义(父Bean定义和子Bean定义合并) public BeanDefinition getMergedBeanDefinition(String name) throws BeansException { String beanName = transformedBeanName(name); // Efficiently check whether bean definition exists in this factory. //若Bean定义不存在,且本容器父工厂为ConfigurableBeanFactory的实例,让父工厂来调用这个方法 if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) { return ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(beanName); } //否则直接从本地合并后的Bean定义中取 return getMergedLocalBeanDefinition(beanName); } public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); Object beanInstance = getSingleton(beanName, false); if (beanInstance != null) { return (beanInstance instanceof FactoryBean); } else if (containsSingleton(beanName)) { // null instance registered return false; } // No singleton instance found -> check bean definition. if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) { // No bean definition found in this factory -> delegate to parent. return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name); } return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName)); } @Override public boolean isActuallyInCreation(String beanName) { return isSingletonCurrentlyInCreation(beanName) || isPrototypeCurrentlyInCreation(beanName); } // 判断指定的原型是否正在被创建 protected boolean isPrototypeCurrentlyInCreation(String beanName) { Object curVal = this.prototypesCurrentlyInCreation.get(); return (curVal != null && (curVal.equals(beanName) || (curVal instanceof Set && ((Set
) curVal).contains(beanName)))); } //原型创建前回调,需要子类重写 @SuppressWarnings("unchecked") protected void beforePrototypeCreation(String beanName) { Object curVal = this.prototypesCurrentlyInCreation.get(); if (curVal == null) { //原型创建状态与当前线程绑定 this.prototypesCurrentlyInCreation.set(beanName); } else if (curVal instanceof String) { Set
beanNameSet = new HashSet
(2); beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } //这里多余了。。。 else { Set
beanNameSet = (Set
) curVal; beanNameSet.add(beanName); } } //创建原型后,从当前线程解除绑定 @SuppressWarnings("unchecked") protected void afterPrototypeCreation(String beanName) { Object curVal = this.prototypesCurrentlyInCreation.get(); if (curVal instanceof String) { this.prototypesCurrentlyInCreation.remove(); } else if (curVal instanceof Set) { Set
beanNameSet = (Set
) curVal; beanNameSet.remove(beanName); if (beanNameSet.isEmpty()) { this.prototypesCurrentlyInCreation.remove(); } } } public void destroyBean(String beanName, Object beanInstance) { destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName)); } /** * Destroy the given bean instance (usually a prototype instance * obtained from this factory) according to the given bean definition. * @param beanName the name of the bean definition * @param beanInstance the bean instance to destroy * @param mbd the merged bean definition */ protected void destroyBean(String beanName, Object beanInstance, RootBeanDefinition mbd) { new DisposableBeanAdapter(beanInstance, beanName, mbd, getBeanPostProcessors(), getAccessControlContext()).destroy(); } public void destroyScopedBean(String beanName) { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); if (mbd.isSingleton() || mbd.isPrototype()) { throw new IllegalArgumentException( "Bean name '" + beanName + "' does not correspond to an object in a mutable scope"); } String scopeName = mbd.getScope(); Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope SPI registered for scope '" + scopeName + "'"); } Object bean = scope.remove(beanName); if (bean != null) { destroyBean(beanName, bean, mbd); } } //--------------------------------------------------------------------- // Implementation methods //--------------------------------------------------------------------- //变换后的Bean名称(先去掉BeanFactory前缀,然后在aliasMap中取标准名) protected String transformedBeanName(String name) { return canonicalName(BeanFactoryUtils.transformedBeanName(name)); } //返回原始的Bean名 protected String originalBeanName(String name) { String beanName = transformedBeanName(name); if (name.startsWith(FACTORY_BEAN_PREFIX)) { beanName = FACTORY_BEAN_PREFIX + beanName; } return beanName; } /** * Initialize the given BeanWrapper with the custom editors registered * with this factory. To be called for BeanWrappers that will create * and populate bean instances. *

The default implementation delegates to { @link #registerCustomEditors}. * Can be overridden in subclasses. * @param bw the BeanWrapper to initialize */ protected void initBeanWrapper(BeanWrapper bw) { bw.setConversionService(getConversionService()); registerCustomEditors(bw); } /** * Initialize the given PropertyEditorRegistry with the custom editors * that have been registered with this BeanFactory. *

To be called for BeanWrappers that will create and populate bean * instances, and for SimpleTypeConverter used for constructor argument * and factory method type conversion. * @param registry the PropertyEditorRegistry to initialize */ protected void registerCustomEditors(PropertyEditorRegistry registry) { PropertyEditorRegistrySupport registrySupport = (registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null); if (registrySupport != null) { registrySupport.useConfigValueEditors(); } if (!this.propertyEditorRegistrars.isEmpty()) { for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) { try { registrar.registerCustomEditors(registry); } catch (BeanCreationException ex) { Throwable rootCause = ex.getMostSpecificCause(); if (rootCause instanceof BeanCurrentlyInCreationException) { BeanCreationException bce = (BeanCreationException) rootCause; if (isCurrentlyInCreation(bce.getBeanName())) { if (logger.isDebugEnabled()) { logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() + "] failed because it tried to obtain currently created bean '" + ex.getBeanName() + "': " + ex.getMessage()); } onSuppressedException(ex); continue; } } throw ex; } } } if (!this.customEditors.isEmpty()) { for (Map.Entry

, Class
> entry : this.customEditors.entrySet()) { Class
requiredType = entry.getKey(); Class
editorClass = entry.getValue(); registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass)); } } } //返回一个合并后的根Bean定义(父Bean定义和子Bean定义合并)(从当前容器取) protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException { // Quick check on the concurrent map first, with minimal locking. RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);//首先直接从合并根定义集合中取 if (mbd != null) { return mbd; } //根据bean名和其对应的Bean定义,取其根Bean根定义 return getMergedBeanDefinition(beanName, getBeanDefinition(beanName)); } //根据Bean名和Bean定义取其Bean根定义 protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd) throws BeanDefinitionStoreException { return getMergedBeanDefinition(beanName, bd, null);//调用重载方法 } //根据Bean名称返回根定义(若给定的Bean定义为子Bean定义,那么合并它的父Bean定义) protected RootBeanDefinition getMergedBeanDefinition( String beanName, BeanDefinition bd, BeanDefinition containingBd) throws BeanDefinitionStoreException { synchronized (this.mergedBeanDefinitions) { RootBeanDefinition mbd = null; //若给定的Bean定义并没有包含子Bean定义,那么直接根据Bean名取根定义 if (containingBd == null) { mbd = this.mergedBeanDefinitions.get(beanName); } if (mbd == null) { //若取不到 if (bd.getParentName() == null) { //若Bean定义没有父类,就很简单了 if (bd instanceof RootBeanDefinition) { //若Bean定义是RootBeanDefinition的实例,克隆、强转后返回 mbd = ((RootBeanDefinition) bd).cloneBeanDefinition(); } else { //否则,根据Bean定义,来构造一个根Bean定义 mbd = new RootBeanDefinition(bd); } } else { //若Bean定义有父类 // Child bean definition: needs to be merged with parent. BeanDefinition pbd; try { String parentBeanName = transformedBeanName(bd.getParentName());//取其父Bean定义的名字 if (!beanName.equals(parentBeanName)) { //若Bean名字并不是bd的父Bean的名字 pbd = getMergedBeanDefinition(parentBeanName);//根据父Bean定义名称来返回合并后的bean定义 } else { //如果beanName对应的Bean就是bd的父Bean if (getParentBeanFactory() instanceof ConfigurableBeanFactory) { //若父Bean工厂为ConfigurableBeanFactory的实例 // 那么强转成ConfigurableBeanFactory后再调用合并方法 pbd = ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(parentBeanName); } else { //若父Bean工厂不是ConfigurableBeanFactory的实例,就抛出异常 throw new NoSuchBeanDefinitionException(bd.getParentName(), "Parent name '" + bd.getParentName() + "' is equal to bean name '" + beanName + "': cannot be resolved without an AbstractBeanFactory parent"); } } } catch (NoSuchBeanDefinitionException ex) { throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName, "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex); } // 深度复制 mbd = new RootBeanDefinition(pbd);//根据Bean定义生成一个根Bean定义 mbd.overrideFrom(bd);//将Bean定义的属性复制进自己的定义(根Bean定义)中 } if (!StringUtils.hasLength(mbd.getScope())) { //如果根Bean定义未设置范围 mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);//那么设置其范围为单例 } // 若本根Bean定义包含Bean定义、本根Bean定义为单例且包含的Bean定义并不是单例 if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) { mbd.setScope(containingBd.getScope());// 那么将本根Bean定义的范围设置为包含的Bean定义的范围 } //若本根Bean定义不包含Bean定义,且是缓存Bean元数据(重写前均为true)且Bean定义是否有资格缓存(默认实现是,这个Bean已经创建便有资格) if (containingBd == null && isCacheBeanMetadata() && isBeanEligibleForMetadataCaching(beanName)) { this.mergedBeanDefinitions.put(beanName, mbd);//放进mergedBeanDefinitions中 } } return mbd; } } //检查Bean定义,抛出异常 protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, Object[] args) throws BeanDefinitionStoreException { if (mbd.isAbstract()) { throw new BeanIsAbstractException(beanName); } if (args != null && !mbd.isPrototype()) { throw new BeanDefinitionStoreException( "Can only specify arguments for the getBean method when referring to a prototype bean definition"); } } /** * Remove the merged bean definition for the specified bean, * recreating it on next access. * @param beanName the bean name to clear the merged definition for */ protected void clearMergedBeanDefinition(String beanName) { this.mergedBeanDefinitions.remove(beanName); } //解析类型,处理异常 protected Class
resolveBeanClass(final RootBeanDefinition mbd, String beanName, final Class
... typesToMatch) throws CannotLoadBeanClassException { try { if (mbd.hasBeanClass()) { return mbd.getBeanClass(); } if (System.getSecurityManager() != null) { return AccessController.doPrivileged(new PrivilegedExceptionAction
>() { public Class
run() throws Exception { return doResolveBeanClass(mbd, typesToMatch); } }, getAccessControlContext()); } else { return doResolveBeanClass(mbd, typesToMatch); } } catch (PrivilegedActionException pae) { ClassNotFoundException ex = (ClassNotFoundException) pae.getException(); throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex); } catch (ClassNotFoundException ex) { throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex); } catch (LinkageError err) { throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err); } } // 真正的解析类型 private Class
doResolveBeanClass(RootBeanDefinition mbd, Class
... typesToMatch) throws ClassNotFoundException { if (!ObjectUtils.isEmpty(typesToMatch)) { ClassLoader tempClassLoader = getTempClassLoader();//找到临时的类加载器 if (tempClassLoader != null) { if (tempClassLoader instanceof DecoratingClassLoader) { //若为装饰类加载器 DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader; for (Class
typeToMatch : typesToMatch) { dcl.excludeClass(typeToMatch.getName()); } } String className = mbd.getBeanClassName(); return (className != null ? ClassUtils.forName(className, tempClassLoader) : null); } } return mbd.resolveBeanClass(getBeanClassLoader()); } /** * Evaluate the given String as contained in a bean definition, * potentially resolving it as an expression. * @param value the value to check * @param beanDefinition the bean definition that the value comes from * @return the resolved value * @see #setBeanExpressionResolver */ protected Object evaluateBeanDefinitionString(String value, BeanDefinition beanDefinition) { if (this.beanExpressionResolver == null) { return value; } Scope scope = (beanDefinition != null ? getRegisteredScope(beanDefinition.getScope()) : null); return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope)); } //预测类型 protected Class
predictBeanType(String beanName, RootBeanDefinition mbd, Class
... typesToMatch) { //若根Bena定义的工厂方法名存在,说明它是工厂Bean创建的,无法预测类型? if (mbd.getFactoryMethodName() != null) { return null; } //否则,解析Bean的Class return resolveBeanClass(mbd, beanName, typesToMatch); } /** * Check whether the given bean is defined as a { @link FactoryBean}. * @param beanName the name of the bean * @param mbd the corresponding bean definition */ protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) { Class
beanType = predictBeanType(beanName, mbd, FactoryBean.class); return (beanType != null && FactoryBean.class.isAssignableFrom(beanType)); } //返回工厂Bean的类型 protected Class
getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) { if (!mbd.isSingleton()) { return null; } try { FactoryBean
factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true); return getTypeForFactoryBean(factoryBean); } catch (BeanCreationException ex) { // Can only happen when getting a FactoryBean. if (logger.isDebugEnabled()) { logger.debug("Ignoring bean creation exception on FactoryBean type check: " + ex); } onSuppressedException(ex); return null; } } //标记这个Bean已经被创建 protected void markBeanAsCreated(String beanName) { this.alreadyCreated.put(beanName, Boolean.TRUE); } /** * Determine whether the specified bean is eligible for having * its bean definition metadata cached. * @param beanName the name of the bean * @return { @code true} if the bean's metadata may be cached * at this point already */ //若本根Bean定义包含Bean元定义作为缓存,这个方法应被之类覆盖,这里仅判断Bean是否已经被创建 protected boolean isBeanEligibleForMetadataCaching(String beanName) { return this.alreadyCreated.containsKey(beanName); } /** * Remove the singleton instance (if any) for the given bean name, * but only if it hasn't been used for other purposes than type checking. * @param beanName the name of the bean * @return { @code true} if actually removed, { @code false} otherwise */ protected boolean removeSingletonIfCreatedForTypeCheckOnly(String beanName) { if (!this.alreadyCreated.containsKey(beanName)) { removeSingleton(beanName); return true; } else { return false; } } //根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 protected Object getObjectForBeanInstance( Object beanInstance, String name, String beanName, RootBeanDefinition mbd) { //如果这个Bean是工厂Bean创建的 且 这个Bean实例并不是FactoryBean实例,抛异常 if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) { throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass()); } //如果这个Bean实例并不是FactoryBean实例 或 这个Bean是工厂Bean创建的,直接返回 if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) { return beanInstance; } //——————————以下都是 这个Bean实例是FactoryBean实例的情况 Object object = null; if (mbd == null) { //若根Bean定义为空,取这个BeanFactory所生产的实例 object = getCachedObjectForFactoryBean(beanName); } if (object == null) { //若取不到,那么手动取 FactoryBean
factory = (FactoryBean
) beanInstance;//把这个实例转化成一个FactoryBean // Caches object obtained from FactoryBean if it is a singleton. if (mbd == null && containsBeanDefinition(beanName)) { //若根Bean定义为空,但是容器内有Bean定义 mbd = getMergedLocalBeanDefinition(beanName);//返回合并后的Bean定义 } boolean synthetic = (mbd != null && mbd.isSynthetic());//标记这个Bean定义是合并的 object = getObjectFromFactoryBean(factory, beanName, !synthetic);//从工厂Bean中取 } return object; } //判断给定的Bean是否被使用过 public boolean isBeanNameInUse(String beanName) { //若是别名 或 并非工厂bean生产出来的 或 被其他某个bean所依赖,那么判断其被使用过 return isAlias(beanName) || containsLocalBean(beanName) || hasDependentBean(beanName); } /** * Determine whether the given bean requires destruction on shutdown. *

The default implementation checks the DisposableBean interface as well as * a specified destroy method and registered DestructionAwareBeanPostProcessors. * @param bean the bean instance to check * @param mbd the corresponding bean definition * @see org.springframework.beans.factory.DisposableBean * @see AbstractBeanDefinition#getDestroyMethodName() * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor */ protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) { return (bean != null && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || hasDestructionAwareBeanPostProcessors())); } /** * Add the given bean to the list of disposable beans in this factory, * registering its DisposableBean interface and/or the given destroy method * to be called on factory shutdown (if applicable). Only applies to singletons. * @param beanName the name of the bean * @param bean the bean instance * @param mbd the bean definition for the bean * @see RootBeanDefinition#isSingleton * @see RootBeanDefinition#getDependsOn * @see #registerDisposableBean * @see #registerDependentBean */ protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) { AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null); if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) { if (mbd.isSingleton()) { // Register a DisposableBean implementation that performs all destruction // work for the given bean: DestructionAwareBeanPostProcessors, // DisposableBean interface, custom destroy method. registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } else { // A bean with a custom scope... Scope scope = this.scopes.get(mbd.getScope()); if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + mbd.getScope() + "'"); } scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } } } //--------------------------------------------------------------------- // Abstract methods to be implemented by subclasses //--------------------------------------------------------------------- //标记是否包含Bean定义的方法 protected abstract boolean containsBeanDefinition(String beanName); //根据Bean名返回其BeanDefinition protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException; //根据指定的bean定义和bean名、参数,创建对象 protected abstract Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException;}

View Code

 

  总结:方法太多了,一个个介绍很浪费时间,不具体介绍。大体介绍一下吧。这个AbstractBeanFactory继承了支持工厂Bean注册的FactoryBeanRegistrySupport,并且实现了BeanFactory重要的第三级接口——ConfigurableBeanFactory。需要具体了解这个接口,可以去看我之前的接口分析—— 。ConfigurableBeanFactory是一个非常复杂的接口,继承了HierarchicalBeanFactory和SingletonBeanRegistry,主要实现了工厂创建、注册Bean、单例类注册等各种功能。

  AbstractBeanFactory实现了ConfigurableBeanFactory接口的绝大多数方法,实现了Bean工厂的许多重要功能,如BeanDefinition、RootBeanDefinition、原型、单例相关的各种操作。

  下面列出一些主要方法实现,其他的方法说明,可具体参照上文我贴出的大部分注释过的源码。

(1)、从容器中获取bean的方法——doGetBean:

@SuppressWarnings("unchecked")    protected 
T doGetBean( final String name, final Class
requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name);//在aliasMap中取得的标准名 Object bean; // Eagerly check singleton cache for manually registered singletons. Object sharedInstance = getSingleton(beanName);//首先在单例集合中取 if (sharedInstance != null && args == null) {//如果取得到,没有指定参数 if (logger.isDebugEnabled()) {//若Log允许调试 if (isSingletonCurrentlyInCreation(beanName)) {//若正准备创建,输出日志 logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); } } 根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { if (isPrototypeCurrentlyInCreation(beanName)) {//如果正在被创建,就抛出异常 throw new BeanCurrentlyInCreationException(beanName); } BeanFactory parentBeanFactory = getParentBeanFactory();//取本容器的父容器 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {//若存在父容器,且本容器不存在对应的Bean定义 String nameToLookup = originalBeanName(name);//取原始的Bean名 if (args != null) {//若参数列表存在 // 那么用父容器根据原始Bean名和参数列表返回 return (T) parentBeanFactory.getBean(nameToLookup, args); } else { // 参数列表不要求,那就直接根据原始名称和要求的类型返回 return parentBeanFactory.getBean(nameToLookup, requiredType); } } //如果不需要类型检查,标记其已经被创建 if (!typeCheckOnly) { markBeanAsCreated(beanName); } //根据beanName取其根Bean定义 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); String[] dependsOn = mbd.getDependsOn();//得到这个根定义的所有依赖 if (dependsOn != null) { for (String dependsOnBean : dependsOn) { getBean(dependsOnBean);//注册这个Bean //注册一个Bean和依赖于它的Bean(后参数依赖前参数) registerDependentBean(dependsOnBean, beanName); } } // 如果Bean定义是单例,就在返回单例 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, new ObjectFactory
() { public Object getObject() throws BeansException { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { destroySingleton(beanName); throw ex; } } }); //根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } //如果是原型 else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName);//原型创建前,与当前线程绑定 prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName);//原型创建后,与当前线程解除绑定 } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else {//既不是单例又不是原型的情况 String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName);//得到范围 if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'"); } try {//根据范围创建实例 Object scopedInstance = scope.get(beanName, new ObjectFactory() { public Object getObject() throws BeansException { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args);//原型创建前,与当前线程绑定 } finally { 原型创建后,与当前线程解除绑定 afterPrototypeCreation(beanName); } } }); //根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; " + "consider defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } } } //判断要求的类型是否和Bean实例的类型正在匹配 if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { try { return getTypeConverter().convertIfNecessary(bean, requiredType);//转换类型,不抛出异常就说明类型匹配 } catch (TypeMismatchException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to convert bean '" + name + "' to required type [" + ClassUtils.getQualifiedName(requiredType) + "]", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; }

  

 

下面对这个方法进行简要的解释:

  <1>、这个方法形参为final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly,分别表示Bean的名称、要求返回的Bean的类型、取Bean时提供的参数数组 以及 是否需要类型检查。哦

  <2>、final String beanName = transformedBeanName(name); 这个方法是从aliasMap中取得对应的标准名。方法实现是,首先去掉name的 FACTORY_BEAN_PREFIX 前缀(如果是工厂Bean本身,那么Bean名有这个前缀),然后调用SimpleAliasRegistry的canonicalName方法。上篇博客已经介绍过SimpleAliasRegistry了,这里贴一下这个方法的源码:

/*     * 根据name这个Key,在aliasMap中不断循环的取对应的value,如果取得到,就继续根据这个value取值,不断循环继续。     * 直到取不到,就把这个在aliasMap中无对应值的key返回。这个动作,叫规范名     */    public String canonicalName(String name) {        String canonicalName = name;    //规范名        // Handle aliasing...        String resolvedName;//已解析名        do {            resolvedName = this.aliasMap.get(canonicalName);//aliasMap中规范名对应的值赋值给已解析名            if (resolvedName != null) {//如果已解析名存在(即规范名在aliasMap中有对应的值)                canonicalName = resolvedName;   // 这个已解析名赋值给标准名            }        } while (resolvedName != null);//不断循环,直到已解析名不存在        return canonicalName;    }

   

  <3>、首先根据标准名beanName,在单例缓存中取对应的Bean:Object sharedInstance = getSingleton(beanName);

  <4>、如果取得到,且args为空,根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例:bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);然后结束整个方法。这个方法源码如下:

//根据给定的实例是否为工厂Bean,返回它自己或工厂Bean创建的实例    protected Object getObjectForBeanInstance(            Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {        //如果这个Bean是工厂Bean创建的 且 这个Bean实例并不是FactoryBean实例,抛异常        if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {            throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());        }        //如果这个Bean实例并不是FactoryBean实例 或 这个Bean是工厂Bean创建的,直接返回        if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {            return beanInstance;        }        //——————————以下都是 这个Bean实例是FactoryBean实例的情况        Object object = null;        if (mbd == null) {//若根Bean定义为空,取这个BeanFactory所生产的实例            object = getCachedObjectForFactoryBean(beanName);        }        if (object == null) {//若取不到,那么手动取            FactoryBean
factory = (FactoryBean
) beanInstance;//把这个实例转化成一个FactoryBean // Caches object obtained from FactoryBean if it is a singleton. if (mbd == null && containsBeanDefinition(beanName)) {//若根Bean定义为空,但是容器内有Bean定义 mbd = getMergedLocalBeanDefinition(beanName);//返回合并后的Bean定义 } boolean synthetic = (mbd != null && mbd.isSynthetic());//标记这个Bean定义是合并的 object = getObjectFromFactoryBean(factory, beanName, !synthetic);//从工厂Bean中取 } return object;

   

  <5>、如果取不到、或 args 不为空(下面都是基于这个条件):

(如果对应的Bean正在被创建,就抛出异常)首先用父容器(如果本容器有的话)根据给出的形参取对应的Bean。

  <6>、此时,判断,如果不需要类型检查,标记其已经被创建。

  <7>、根据beanName取本地合并后的RootBeanDefinition(这个方法getMergedLocalBeanDefinition涉及到多层BeanDefinition相关的调用),然后检查一下。然后根据这个RootBeanDefinition,注册这个Bean和它的所有依赖。

  <8>、如果这个RootBeanDefinition是单例,先根据beanName从单例缓存中取,取不到就创建一个匿名内部Bean工厂,创建一个单例,直接结束方法。

  <9>、如果这个RootBeanDefinition是原型,就直接创建一个Bean返回,并在创建前把beanName与当前线程绑定,创建后解绑。

  <10>、如果这个RootBeanDefinition既不是单例,又不是原型,那么根据这个RootBeanDefinition定义的范围Scope,直接创建一个scopedInstance。

  <11>、若这个scopedInstance为工厂Bean,就得到它创建的实例,否则得到它自身。

  <12>、对<9>或<11>中最后产生的Bean就进行一次检查,要求这个产生的Bean的类型是否和Bean实例的类型匹配,不匹配就抛出异常。

  以上就是这个doGetBean方法了。其他的方法分析可参照上文的源码。

转载于:https://www.cnblogs.com/JiangWJ/p/10800257.html

你可能感兴趣的文章
Python数据分析_Pandas01_数据框的创建和选取
查看>>
RESTful-rest_framework应用第一篇
查看>>
Console命令详解,让调试js代码变得更简单
查看>>
hdu4908 &amp; BestCoder Round #3 BestCoder Sequence(组合数学)
查看>>
Excel 导出
查看>>
拉登是我罩的队_第三周_需求改进&原型设计
查看>>
数据库got error 28 from storage engine问题
查看>>
RMQ 总结
查看>>
手撸ORM
查看>>
POJ---2406 Power Strings[求最长重复字串]
查看>>
005-(已测试成功的方案)kickstart模式实现批量安装centos7.x系统
查看>>
linux搭建haproxy
查看>>
Oracle update 日期
查看>>
【t088】倒水
查看>>
【t016】邮递员
查看>>
boost安装
查看>>
Vue与React的异同
查看>>
360:跳高游戏
查看>>
CSS3 Background-size
查看>>
Python Ethical Hacking - MAC Address & How to Change(3)
查看>>