Spring 学习记录6 BeanFactory(2)
主题
除了Spring 学习记录5 BeanFactory 里写的几个接口外,BeanFactory的实现类还实现了一些其他接口,这篇文章主要介绍这些接口和实现类.
结构
DefaultListableBeanFactory和它的父类们除了实现了BF的各种接口以外还实现了AliasRegistry和BeanDefinitionRegistry接口.而且不同等级的父类和BF的相关接口都有交集..
AliasRegistry
这个接口根据说明来看意思是提供别名注册的服务.虽然没有实际使用过别名,不过1个bean确实可以有N个别名.


1 /* 2 * Copyright 2002-2008 the original author or authors.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *http://www.apache.org/licenses/LICENSE-2.0 9 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */ 16 17 packageorg.springframework.core;18 19 /** 20 * Common interface for managing aliases. Serves as super-interface for21 * {@linkorg.springframework.beans.factory.support.BeanDefinitionRegistry}.22 *23 *@authorJuergen Hoeller24 *@since2.5.225 */ 26 public interfaceAliasRegistry {27 28 /** 29 * Given a name, register an alias for it.30 *@paramname the canonical name31 *@paramalias the alias to be registered32 *@throwsIllegalStateException if the alias is already in use33 * and may not be overridden34 */ 35 voidregisterAlias(String name, String alias);36 37 /** 38 * Remove the specified alias from this registry.39 *@paramalias the alias to remove40 *@throwsIllegalStateException if no such alias was found41 */ 42 voidremoveAlias(String alias);43 44 /** 45 * Determine whether this given name is defines as an alias46 * (as opposed to the name of an actually registered component).47 *@parambeanName the bean name to check48 *@returnwhether the given name is an alias49 */ 50 booleanisAlias(String beanName);51 52 /** 53 * Return the aliases for the given name, if defined.54 *@paramname the name to check for aliases55 *@returnthe aliases, or an empty array if none56 */ 57 String[] getAliases(String name);58 59 }
View Code
接口就4个方法.
1.为1个beanname注册1个别名,
2.删除1个别名
3.判断1个name是否是别名
4.根据beanname获取所有别名.
SimpleAliasRegistry
这个类实现了AliasRegistry,用了1个ConcurrentHashMap来存储所有别名的映射关系.
测试代码:
1 packagespring.bf;2 3 importorg.junit.Test;4 importorg.junit.runner.RunWith;5 importorg.springframework.core.SimpleAliasRegistry;6 importorg.springframework.test.context.ContextConfiguration;7 importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;8 importorg.springframework.util.StringValueResolver;9 10 importjava.util.Arrays;11 12 @RunWith(SpringJUnit4ClassRunner.class)13 @ContextConfiguration("classpath:test-application-context.xml")14 public classSimpleAliasRegistryTest {15 16 SimpleAliasRegistry simpleAliasRegistry = newSimpleAliasRegistry();17 18 /** 19 * 别名不能循环引用20 * 会调用checkForAliasCircle方法,做循环引用的检查21 * 里面会调用canonicalName方法,这个方法会不停的用传入的name当做别名去找他对应的beanname,层层找下去,找到最后1个beanname以后和alias比较一下,如果一直,说明有循环引用就抛出异常22 */ 23 @Test24 public voidtest() {25 simpleAliasRegistry.registerAlias("b1", "a1");26 simpleAliasRegistry.registerAlias("a1", "a2");27 //simpleAliasRegistry.registerAlias("a2", "b1");//java.lang.IllegalStateException: Cannot register alias 'b1' for name 'a2': Circular reference - 'a2' is a direct or indirect alias for 'b1' already 28 }29 30 /** 31 * 默认情况下别名可以覆盖32 * 根据子类会不会重写allowAliasOverriding来做决定,默认是true33 */ 34 @Test35 public voidtest2() {36 simpleAliasRegistry.registerAlias("b1", "a1");37 simpleAliasRegistry.registerAlias("b2", "a1");38 System.out.println(Arrays.toString(simpleAliasRegistry.getAliases("b1"))); //[] 39 System.out.println(Arrays.toString(simpleAliasRegistry.getAliases("b2"))); //[a1] 40 }41 42 /** 43 * 移除不存在的bean会抛异常44 * 所以调用之前可以先用isAlias做判断45 */ 46 @Test47 public voidtest3() {48 //simpleAliasRegistry.removeAlias("not exists");//java.lang.IllegalStateException: No alias 'not exists' registered 49 }50 51 //getAliases会调用retrieveAliases方法,它会递归调用自身,根据beanname找到alias,再把alias当做beanname,把所有的alias都找出来. 52 53 /** 54 * 测试resolveAliases方法55 */ 56 @Test57 public voidtest4() {58 simpleAliasRegistry.registerAlias("b1", "a1");59 simpleAliasRegistry.registerAlias("b2", "a2");60 //报错61 //java.lang.IllegalStateException: Cannot register resolved alias 'a1' (original: 'a2') for name 'b2': It is already registered for name 'b2'.62 //提示感觉有问题.其实应该提示It is already registered for name 'b1'.63 //因为alias a2 被解析为a1, 而a1已经指向的是beanname b1,所以不能再指向b2 64 simpleAliasRegistry.resolveAliases(newStringValueResolver() {65 @Override66 publicString resolveStringValue(String strVal) {67 if (strVal.equals("a2")) {68 return "a1";69 }70 returnstrVal;71 }72 });73 }74 }
方法基本在测试里都测了.
另外感觉resolveAliases有一个提示有点问题,请参test4方法.
DefaultSingletonBeanRegistry
直接上注释吧...很多方法目前还不知道为什么这么写.什么时候会用到.看到后面的子类可能就会懂了.


1 /* 2 * Copyright 2002-2015 the original author or authors.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *http://www.apache.org/licenses/LICENSE-2.0 9 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */ 16 17 packageorg.springframework.beans.factory.support;18 19 importorg.apache.commons.logging.Log;20 importorg.apache.commons.logging.LogFactory;21 import org.springframework.beans.factory.*;22 importorg.springframework.beans.factory.config.SingletonBeanRegistry;23 importorg.springframework.core.SimpleAliasRegistry;24 importorg.springframework.util.Assert;25 importorg.springframework.util.StringUtils;26 27 import java.util.*;28 importjava.util.concurrent.ConcurrentHashMap;29 30 /** 31 * Generic registry for shared bean instances, implementing the32 * {@linkorg.springframework.beans.factory.config.SingletonBeanRegistry}.33 * Allows for registering singleton instances that should be shared34 * for all callers of the registry, to be obtained via bean name.35 * <p>36 * <p>Also supports registration of37 * {@linkorg.springframework.beans.factory.DisposableBean} instances,38 * (which might or might not correspond to registered singletons),39 * to be destroyed on shutdown of the registry. Dependencies between40 * beans can be registered to enforce an appropriate shutdown order.41 * <p>42 * <p>This class mainly serves as base class for43 * {@linkorg.springframework.beans.factory.BeanFactory} implementations,44 * factoring out the common management of singleton bean instances. Note that45 * the {@linkorg.springframework.beans.factory.config.ConfigurableBeanFactory}46 * interface extends the {@linkSingletonBeanRegistry} interface.47 * <p>48 * <p>Note that this class assumes neither a bean definition concept49 * nor a specific creation process for bean instances, in contrast to50 * {@linkAbstractBeanFactory} and {@linkDefaultListableBeanFactory}51 * (which inherit from it). Can alternatively also be used as a nested52 * helper to delegate to.53 *54 *@authorJuergen Hoeller55 *@see#registerSingleton56 *@see#registerDisposableBean57 *@seeorg.springframework.beans.factory.DisposableBean58 *@seeorg.springframework.beans.factory.config.ConfigurableBeanFactory59 *@since2.060 */ 61 public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implementsSingletonBeanRegistry {62 63 /** 64 * Internal marker for a null singleton object:65 * used as marker value for concurrent Maps (which don't support null values).66 * concurrent Maps里不能put null,所以用这个代替67 */ 68 protected static final Object NULL_OBJECT = newObject();69 70 71 /** 72 * Logger available to subclasses73 */ 74 protected final Log logger =LogFactory.getLog(getClass());75 76 /** 77 * Cache of singleton objects: bean name --> bean instance78 * 存单例的bean,FactoryBean也算79 */ 80 private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);81 82 /** 83 * Cache of singleton factories: bean name --> ObjectFactory84 * 存ObjectFactory,我自己没用过.85 * 测试的时候发现有循环引用的时候.比如A,B相互引用的时候,先扫描到A注册A.当前工厂的一个内部类对象会被注册到这里.有1个bean的引用指向B86 */ 87 private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);88 89 /** 90 * Cache of early singleton objects: bean name --> bean instance91 * 一般情况下可能这个map都是空的,只有2个bean相互引用的时候才会有值.92 * 看英文解释似乎是一个bean还没被完全创建完的时候会被丢到这个map里.可能作用是先让其他bean先能够引用这个bean吧93 * 测试A和B相互引用,先扫描到A的话A会放到这里里面,然后开始注册B,B注册完了再remove94 */ 95 private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);96 97 /** 98 * Set of registered singletons, containing the bean names in registration order99 * 注册的bean的name都会放到这里100 */ 101 private final Set<String> registeredSingletons = new LinkedHashSet<String>(64);102 103 /** 104 * Names of beans that are currently in creation105 * 注册A的时候如果A和B相互引用,A会被放到这里里面.和earlySingletonObjects一起使用106 */ 107 private final Set<String> singletonsCurrentlyInCreation = 108 Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));109 110 /** 111 * Names of beans currently excluded from in creation checks112 * 创建bean过程中有一些bean已经在创建了在创建会报错,用这个可以排除掉这个检查,不知道啥时候会用到113 */ 114 private final Set<String> inCreationCheckExclusions = 115 Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));116 117 /** 118 * List of suppressed Exceptions, available for associating related causes119 * 创建bean过程中出现一些特定的错误的时候可以无视这些错误继续创建120 */ 121 private Set<Exception>suppressedExceptions;122 123 /** 124 * Flag that indicates whether we're currently within destroySingletons125 * 是否正在销毁bean,可能是factory在destroy的时候就不能再创建bean了126 */ 127 private boolean singletonsCurrentlyInDestruction = false;128 129 /** 130 * Disposable bean instances: bean name --> disposable instance131 * 存disposableBean132 */ 133 private final Map<String, Object> disposableBeans = new LinkedHashMap<String, Object>();134 135 /** 136 * Map between containing bean names: bean name --> Set of bean names that the bean contains137 * 似乎是用在innerbean和outerbean的时候使用.我一直没使用过这种bean138 */ 139 private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<String, Set<String>>(16);140 141 /** 142 * Map between dependent bean names: bean name --> Set of dependent bean names143 * A中有B,那key就是B,value就是A.销毁B之前需要先销毁A144 */ 145 private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<String, Set<String>>(64);146 147 /** 148 * Map between depending bean names: bean name --> Set of bean names for the bean's dependencies149 * 和dependentBeanMap刚好相反,A中有B和C的引用.那key是A value是B和C150 */ 151 private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<String, Set<String>>(64);152 153 154 /** 155 * 注册单例bean156 *157 *@parambeanName158 *@paramsingletonObject159 *@throwsIllegalStateException160 */ 161 @Override162 public void registerSingleton(String beanName, Object singletonObject) throwsIllegalStateException {163 Assert.notNull(beanName, "'beanName' must not be null");164 synchronized (this.singletonObjects) {165 Object oldObject = this.singletonObjects.get(beanName);166 //从singletonObjects获取bean,有bean说明已经注册过了不让重新注册 167 if (oldObject != null) {168 throw new IllegalStateException("Could not register object [" + singletonObject + 169 "] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");170 }171 //没注册过就掉注册方法 172 addSingleton(beanName, singletonObject);173 }174 }175 176 /** 177 * Add the given singleton object to the singleton cache of this factory.178 * <p>To be called for eager registration of singletons.179 * 注册1个单例bean180 *181 *@parambeanName the name of the bean182 *@paramsingletonObject the singleton object183 */ 184 protected voidaddSingleton(String beanName, Object singletonObject) {185 synchronized (this.singletonObjects) {186 //注册的单例bean放到singletonObjects和registeredSingletons里,null的话为了防止map抛出异常所以要put一个默认的obj187 //但是我也不知道为什么时候add的时候singletonFactories和earlySingletonObjects会有值,需要remove. 188 this.singletonObjects.put(beanName, (singletonObject != null ?singletonObject : NULL_OBJECT));189 this.singletonFactories.remove(beanName);190 this.earlySingletonObjects.remove(beanName);191 this.registeredSingletons.add(beanName);192 }193 }194 195 /** 196 * Add the given singleton factory for building the specified singleton197 * if necessary.198 * <p>To be called for eager registration of singletons, e.g. to be able to199 * resolve circular references.200 * 和addSingleton几乎一样的道理201 *202 *@parambeanName the name of the bean203 *@paramsingletonFactory the factory for the singleton object204 */ 205 protected void addSingletonFactory(String beanName, ObjectFactory<?>singletonFactory) {206 Assert.notNull(singletonFactory, "Singleton factory must not be null");207 synchronized (this.singletonObjects) {208 if (!this.singletonObjects.containsKey(beanName)) {209 this.singletonFactories.put(beanName, singletonFactory);210 this.earlySingletonObjects.remove(beanName);211 this.registeredSingletons.add(beanName);212 }213 }214 }215 216 @Override217 publicObject getSingleton(String beanName) {218 return getSingleton(beanName, true);219 }220 221 /** 222 * Return the (raw) singleton object registered under the given name.223 * <p>Checks already instantiated singletons and also allows for an early224 * reference to a currently created singleton (resolving a circular reference).225 * 获取一个单例226 *227 *@parambeanName the name of the bean to look for228 *@paramallowEarlyReference whether early references should be created or not229 *@returnthe registered singleton object, or {@codenull} if none found230 */ 231 protected Object getSingleton(String beanName, booleanallowEarlyReference) {232 Object singletonObject = this.singletonObjects.get(beanName);233 //从singletonObjects中先获取,如果非空就直接返回,如果是空的,判断是否正在创建中 234 if (singletonObject == null &&isSingletonCurrentlyInCreation(beanName)) {235 synchronized (this.singletonObjects) {236 //如果正在创建就从earlySingletonObjects中获取A,B相互引用先加载A的时候A会被先放到earlySingletonObjects中而不是singletonObjects中,因为A还没创建就需要创建B 237 singletonObject = this.earlySingletonObjects.get(beanName);238 //目前我还没遇到过allowEarlyReference为true的情况 239 if (singletonObject == null &&allowEarlyReference) {240 ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);241 if (singletonFactory != null) {242 singletonObject =singletonFactory.getObject();243 this.earlySingletonObjects.put(beanName, singletonObject);244 this.singletonFactories.remove(beanName);245 }246 }247 }248 }249 return (singletonObject != NULL_OBJECT ? singletonObject : null);250 }251 252 /** 253 * Return the (raw) singleton object registered under the given name,254 * creating and registering a new one if none registered yet.255 * 也是获取bean,但是没有的时候可以从工厂里获取256 *257 *@parambeanName the name of the bean258 *@paramsingletonFactory the ObjectFactory to lazily create the singleton259 * with, if necessary260 *@returnthe registered singleton object261 */ 262 public Object getSingleton(String beanName, ObjectFactory<?>singletonFactory) {263 Assert.notNull(beanName, "'beanName' must not be null");264 synchronized (this.singletonObjects) {265 //获取bean 266 Object singletonObject = this.singletonObjects.get(beanName);267 if (singletonObject == null) {268 //如果工厂正在destroy.就直接抛异常 269 if (this.singletonsCurrentlyInDestruction) {270 throw newBeanCreationNotAllowedException(beanName,271 "Singleton bean creation not allowed while the singletons of this factory are in destruction " + 272 "(Do not request a bean from a BeanFactory in a destroy method implementation!)");273 }274 if(logger.isDebugEnabled()) {275 logger.debug("Creating shared instance of singleton bean '" + beanName + "'");276 }277 //创建之前做校验,如果已经正在创建了.就报错. 278 beforeSingletonCreation(beanName);279 boolean newSingleton = false;280 boolean recordSuppressedExceptions = (this.suppressedExceptions == null);281 if(recordSuppressedExceptions) {282 this.suppressedExceptions = new LinkedHashSet<Exception>();283 }284 try{285 //从工厂里获取 286 singletonObject =singletonFactory.getObject();287 newSingleton = true;288 } catch(IllegalStateException ex) {289 //Has the singleton object implicitly appeared in the meantime ->290 //if yes, proceed with it since the exception indicates that state.291 //之前有 同步 不知道什么时候会进这条分支 292 singletonObject = this.singletonObjects.get(beanName);293 if (singletonObject == null) {294 throwex;295 }296 } catch(BeanCreationException ex) {297 //如果创建报错了.就把之前抑制的错误一起抛出,不过这个方法里没看到有添加抑制错误的. 298 if(recordSuppressedExceptions) {299 for (Exception suppressedException : this.suppressedExceptions) {300 ex.addRelatedCause(suppressedException);301 }302 }303 throwex;304 } finally{305 if(recordSuppressedExceptions) {306 this.suppressedExceptions = null;307 }308 //把之前的singletonsCurrentlyInCreation添加的正在创建的bean删掉 309 afterSingletonCreation(beanName);310 }311 //如果是新创建了bean就添加到相应的map里 312 if(newSingleton) {313 addSingleton(beanName, singletonObject);314 }315 }316 return (singletonObject != NULL_OBJECT ? singletonObject : null);317 }318 }319 320 /** 321 * Register an Exception that happened to get suppressed during the creation of a322 * singleton bean instance, e.g. a temporary circular reference resolution problem.323 * 添加需要抑制的错误,创建过程中如果报了这些错误,不算出错.本类中没被调用324 *325 *@paramex the Exception to register326 */ 327 protected voidonSuppressedException(Exception ex) {328 synchronized (this.singletonObjects) {329 if (this.suppressedExceptions != null) {330 this.suppressedExceptions.add(ex);331 }332 }333 }334 335 /** 336 * Remove the bean with the given name from the singleton cache of this factory,337 * to be able to clean up eager registration of a singleton if creation failed.338 * 移除一个单例bean339 *340 *@parambeanName the name of the bean341 *@see#getSingletonMutex()342 */ 343 protected voidremoveSingleton(String beanName) {344 synchronized (this.singletonObjects) {345 this.singletonObjects.remove(beanName);346 this.singletonFactories.remove(beanName);347 this.earlySingletonObjects.remove(beanName);348 this.registeredSingletons.remove(beanName);349 }350 }351 352 @Override353 public booleancontainsSingleton(String beanName) {354 return this.singletonObjects.containsKey(beanName);355 }356 357 @Override358 publicString[] getSingletonNames() {359 synchronized (this.singletonObjects) {360 return StringUtils.toStringArray(this.registeredSingletons);361 }362 }363 364 @Override365 public intgetSingletonCount() {366 synchronized (this.singletonObjects) {367 return this.registeredSingletons.size();368 }369 }370 371 372 /** 373 * 设置一个bean正在被创建的标志,其实是放到一个跳过检查的set里.在这个set里的bean都会跳过检查.不然正在创建又执行创建需要抛出异常374 *@parambeanName375 *@paraminCreation376 */ 377 public void setCurrentlyInCreation(String beanName, booleaninCreation) {378 Assert.notNull(beanName, "Bean name must not be null");379 if (!inCreation) {380 this.inCreationCheckExclusions.add(beanName);381 } else{382 this.inCreationCheckExclusions.remove(beanName);383 }384 }385 386 public booleanisCurrentlyInCreation(String beanName) {387 Assert.notNull(beanName, "Bean name must not be null");388 return (!this.inCreationCheckExclusions.contains(beanName) &&isActuallyInCreation(beanName));389 }390 391 /** 392 * setCurrentlyInCreation方法只是用1个set集合记录需要跳过检查步骤的bean,singletonsCurrentlyInCreation里存的bean才是真正正在创建的bean393 *@parambeanName394 *@return 395 */ 396 protected booleanisActuallyInCreation(String beanName) {397 returnisSingletonCurrentlyInCreation(beanName);398 }399 400 /** 401 * Return whether the specified singleton bean is currently in creation402 * (within the entire factory).403 * 参考isActuallyInCreation方法404 *405 *@parambeanName the name of the bean406 */ 407 public booleanisSingletonCurrentlyInCreation(String beanName) {408 return this.singletonsCurrentlyInCreation.contains(beanName);409 }410 411 /** 412 * Callback before singleton creation.413 * <p>The default implementation register the singleton as currently in creation.414 * 在ObjectFactory创建bean之前检查一下是否已经正在创建这个bean了.415 *416 *@parambeanName the name of the singleton about to be created417 *@see#isSingletonCurrentlyInCreation418 */ 419 protected voidbeforeSingletonCreation(String beanName) {420 if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {421 throw newBeanCurrentlyInCreationException(beanName);422 }423 }424 425 /** 426 * Callback after singleton creation.427 * <p>The default implementation marks the singleton as not in creation anymore.428 * 在ObjectFactory创建bean之后,需要这个bean正在创建的标志移除429 *430 *@parambeanName the name of the singleton that has been created431 *@see#isSingletonCurrentlyInCreation432 */ 433 protected voidafterSingletonCreation(String beanName) {434 if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {435 throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");436 }437 }438 439 440 /** 441 * Add the given bean to the list of disposable beans in this registry.442 * <p>Disposable beans usually correspond to registered singletons,443 * matching the bean name but potentially being a different instance444 * (for example, a DisposableBean adapter for a singleton that does not445 * naturally implement Spring's DisposableBean interface).446 * 注册DisposableBean447 *448 *@parambeanName the name of the bean449 *@parambean the bean instance450 */ 451 public voidregisterDisposableBean(String beanName, DisposableBean bean) {452 synchronized (this.disposableBeans) {453 this.disposableBeans.put(beanName, bean);454 }455 }456 457 /** 458 * Register a containment relationship between two beans,459 * e.g. between an inner bean and its containing outer bean.460 * <p>Also registers the containing bean as dependent on the contained bean461 * in terms of destruction order.462 * 注册嵌套的bean.我从来没用过.463 *464 *@paramcontainedBeanName the name of the contained (inner) bean 内部bean465 *@paramcontainingBeanName the name of the containing (outer) bean 外部bean466 *@see#registerDependentBean467 */ 468 public voidregisterContainedBean(String containedBeanName, String containingBeanName) {469 //A quick check for an existing entry upfront, avoiding synchronization... 470 Set<String> containedBeans = this.containedBeanMap.get(containingBeanName);471 if (containedBeans != null &&containedBeans.contains(containedBeanName)) {472 return;473 }474 475 //No entry yet -> fully synchronized manipulation of the containedBeans Set 476 synchronized (this.containedBeanMap) {477 containedBeans = this.containedBeanMap.get(containingBeanName);478 if (containedBeans == null) {479 containedBeans = new LinkedHashSet<String>(8);480 this.containedBeanMap.put(containingBeanName, containedBeans);481 }482 containedBeans.add(containedBeanName);483 }484 registerDependentBean(containedBeanName, containingBeanName);485 }486 487 /** 488 * Register a dependent bean for the given bean,489 * to be destroyed before the given bean is destroyed.490 * 注册相互依赖的bean.比如A中有B.dependentBeanMap里key是B,value是A.需要先销毁A再销毁B491 * dependenciesForBeanMap刚好相反.可以参考之前成员域上的注释492 *493 *@parambeanName the name of the bean494 *@paramdependentBeanName the name of the dependent bean495 */ 496 public voidregisterDependentBean(String beanName, String dependentBeanName) {497 //A quick check for an existing entry upfront, avoiding synchronization...498 //先把别名转化到真正的bean name 499 String canonicalName =canonicalName(beanName);500 Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);501 if (dependentBeans != null &&dependentBeans.contains(dependentBeanName)) {502 return;503 }504 505 //No entry yet -> fully synchronized manipulation of the dependentBeans Set506 //依赖之前没注册过就注册到相应的map里去 507 synchronized (this.dependentBeanMap) {508 dependentBeans = this.dependentBeanMap.get(canonicalName);509 if (dependentBeans == null) {510 dependentBeans = new LinkedHashSet<String>(8);511 this.dependentBeanMap.put(canonicalName, dependentBeans);512 }513 dependentBeans.add(dependentBeanName);514 }515 synchronized (this.dependenciesForBeanMap) {516 Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName);517 if (dependenciesForBean == null) {518 dependenciesForBean = new LinkedHashSet<String>(8);519 this.dependenciesForBeanMap.put(dependentBeanName, dependenciesForBean);520 }521 dependenciesForBean.add(canonicalName);522 }523 }524 525 /** 526 * Determine whether the specified dependent bean has been registered as527 * dependent on the given bean or on any of its transitive dependencies.528 * 判断2个bean是否有依赖关系529 *530 *@parambeanName the name of the bean to check531 *@paramdependentBeanName the name of the dependent bean532 *@since4.0533 */ 534 protected booleanisDependent(String beanName, String dependentBeanName) {535 return isDependent(beanName, dependentBeanName, null);536 }537 538 /** 539 * 判断2个bean是否有依赖关系,A中有B,B中有C,那C依赖A是true.540 *@parambeanName541 *@paramdependentBeanName542 *@paramalreadySeen543 *@return 544 */ 545 private boolean isDependent(String beanName, String dependentBeanName, Set<String>alreadySeen) {546 String canonicalName =canonicalName(beanName);547 if (alreadySeen != null &&alreadySeen.contains(beanName)) {548 return false;549 }550 //canonicalName是C dependentBeans是B 551 Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);552 if (dependentBeans == null) {553 return false;554 }555 if(dependentBeans.contains(dependentBeanName)) {556 return true;557 }558 //第一轮没找到A只找到包含B的一个set.所以再便利这个set.去看这个set里的bean是否依赖A,但是可能会有循环引用.所以找过的bean需要记录,不需要再找 559 for(String transitiveDependency : dependentBeans) {560 if (alreadySeen == null) {561 alreadySeen = new HashSet<String>();562 }563 alreadySeen.add(beanName); //已经找过的bean放到这里.C已经找过了. 564 if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) { //递归调用,判断B是否依赖A,是true.而C依赖B,所以C依赖A 565 return true;566 }567 }568 return false;569 }570 571 /** 572 * Determine whether a dependent bean has been registered for the given name.573 *574 *@parambeanName the name of the bean to check575 */ 576 protected booleanhasDependentBean(String beanName) {577 return this.dependentBeanMap.containsKey(beanName);578 }579 580 /** 581 * Return the names of all beans which depend on the specified bean, if any.582 *583 *@parambeanName the name of the bean584 *@returnthe array of dependent bean names, or an empty array if none585 */ 586 publicString[] getDependentBeans(String beanName) {587 Set<String> dependentBeans = this.dependentBeanMap.get(beanName);588 if (dependentBeans == null) {589 return new String[0];590 }591 returnStringUtils.toStringArray(dependentBeans);592 }593 594 /** 595 * Return the names of all beans that the specified bean depends on, if any.596 *597 *@parambeanName the name of the bean598 *@returnthe array of names of beans which the bean depends on,599 * or an empty array if none600 */ 601 publicString[] getDependenciesForBean(String beanName) {602 Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName);603 if (dependenciesForBean == null) {604 return new String[0];605 }606 return dependenciesForBean.toArray(newString[dependenciesForBean.size()]);607 }608 609 /** 610 * 销毁单例bean611 */ 612 public voiddestroySingletons() {613 if(logger.isDebugEnabled()) {614 logger.debug("Destroying singletons in " + this);615 }616 //设置正在销毁的标志 617 synchronized (this.singletonObjects) {618 this.singletonsCurrentlyInDestruction = true;619 }620 621 String[] disposableBeanNames;622 synchronized (this.disposableBeans) {623 disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());624 }625 //取出所有disposableBeans然后调用每个bean都调用相应的销毁方法 626 for (int i = disposableBeanNames.length - 1; i >= 0; i--) {627 destroySingleton(disposableBeanNames[i]);628 }629 630 //所有缓存清空 631 this.containedBeanMap.clear();632 this.dependentBeanMap.clear();633 this.dependenciesForBeanMap.clear();634 635 synchronized (this.singletonObjects) {636 this.singletonObjects.clear();637 this.singletonFactories.clear();638 this.earlySingletonObjects.clear();639 this.registeredSingletons.clear();640 this.singletonsCurrentlyInDestruction = false;641 }642 }643 644 /** 645 * Destroy the given bean. Delegates to {@codedestroyBean}646 * if a corresponding disposable bean instance is found.647 *648 *@parambeanName the name of the bean649 *@see#destroyBean650 */ 651 public voiddestroySingleton(String beanName) {652 //Remove a registered singleton of the given name, if any. 653 removeSingleton(beanName);654 655 //Destroy the corresponding DisposableBean instance. 656 DisposableBean disposableBean;657 synchronized (this.disposableBeans) {658 disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);659 }660 destroyBean(beanName, disposableBean);661 }662 663 /** 664 * Destroy the given bean. Must destroy beans that depend on the given665 * bean before the bean itself. Should not throw any exceptions.666 *667 *@parambeanName the name of the bean668 *@parambean the bean instance to destroy669 */ 670 protected voiddestroyBean(String beanName, DisposableBean bean) {671 //Trigger destruction of dependent beans first...672 //销毁1个bean的时候需要按顺序,先销毁引用她的bean,再销毁他自己 673 Set<String> dependencies = this.dependentBeanMap.remove(beanName);674 if (dependencies != null) {675 if(logger.isDebugEnabled()) {676 logger.debug("Retrieved dependent beans for bean '" + beanName + "': " +dependencies);677 }678 for(String dependentBeanName : dependencies) {679 //对于每个引用这个bean的所有bean,先销毁他们,再销毁当前这个beanName对应的bean,A中有B需要先销毁A 680 destroySingleton(dependentBeanName);681 }682 }683 684 //Actually destroy the bean now... 685 if (bean != null) {686 try{687 bean.destroy(); //DisposableBean接口的方法 688 } catch(Throwable ex) {689 logger.error("Destroy method on bean with name '" + beanName + "' threw an exception", ex);690 }691 }692 693 //Trigger destruction of contained beans...694 //对于内部bean也一样,先销毁外部的bean 695 Set<String> containedBeans = this.containedBeanMap.remove(beanName);696 if (containedBeans != null) {697 for(String containedBeanName : containedBeans) {698 destroySingleton(containedBeanName);699 }700 }701 702 //Remove destroyed bean from other beans' dependencies.703 //销毁了这个bean,那dependentBeanMap中如果其他bean依赖这个bean,就都可以移除这个bean的引用.比如A中有B和C类.destroyB的时候需要先destroy A704 //那destroy A了以后因为C也依赖A.所以也要把dependentBeanMap的key c 对应的vaalue A也删除,不然下次删除C的时候又要删除A.这样就重复destroy A了. 705 synchronized (this.dependentBeanMap) {706 for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext(); ) {707 Map.Entry<String, Set<String>> entry =it.next();708 Set<String> dependenciesToClean =entry.getValue();709 dependenciesToClean.remove(beanName);710 if(dependenciesToClean.isEmpty()) {711 it.remove();712 }713 }714 }715 716 //Remove destroyed bean's prepared dependency information. 717 this.dependenciesForBeanMap.remove(beanName);718 }719 720 /** 721 * Exposes the singleton mutex to subclasses and external collaborators.722 * <p>Subclasses should synchronize on the given Object if they perform723 * any sort of extended singleton creation phase. In particular, subclasses724 * should <i>not</i> have their own mutexes involved in singleton creation,725 * to avoid the potential for deadlocks in lazy-init situations.726 */ 727 public finalObject getSingletonMutex() {728 return this.singletonObjects;729 }730 731 }
View Code
FactoryBeanRegistrySupport
这个类基本上和它的父类DefaultSingletonBeanRegistry功能差不多.就是多了1个叫做factoryBeanObjectCache的map去缓存FactoryBean生成的bean...代码写法都大同小异..我想分享下期中的1个方法
1 /** 2 * Obtain an object to expose from the given FactoryBean.3 *4 *@paramfactory the FactoryBean instance5 *@parambeanName the name of the bean6 *@paramshouldPostProcess whether the bean is subject to post-processing7 *@returnthe object obtained from the FactoryBean8 *@throwsBeanCreationException if FactoryBean object creation failed9 *@seeorg.springframework.beans.factory.FactoryBean#getObject()10 */ 11 protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, booleanshouldPostProcess) {12 if (factory.isSingleton() && containsSingleton(beanName)) { //FactoryBean返回的对象是单例并且FactoryBean(不是返回的对象)这个bean已经在缓存中了 13 synchronized(getSingletonMutex()) {14 Object object = this.factoryBeanObjectCache.get(beanName); //从缓存里拿FactoryBean的返回对象 15 if (object == null) { //没缓存的话 16 object = doGetObjectFromFactoryBean(factory, beanName); //就重新生成17 //Only post-process and store if not put there already during getObject() call above18 //(e.g. because of circular reference processing triggered by custom getBean calls) 19 Object alreadyThere = this.factoryBeanObjectCache.get(beanName); //不懂为什么上面去过一次是null了需要再取几次...什么时候会发生呢? 20 if (alreadyThere != null) {21 object =alreadyThere;22 } else{23 if (object != null &&shouldPostProcess) {24 try{25 object = postProcessObjectFromFactoryBean(object, beanName); //后置处理 26 } catch(Throwable ex) {27 throw newBeanCreationException(beanName,28 "Post-processing of FactoryBean's singleton object failed", ex);29 }30 }31 this.factoryBeanObjectCache.put(beanName, (object != null ?object : NULL_OBJECT));32 }33 }34 return (object != NULL_OBJECT ? object : null);35 }36 } else { //不是单例,或者第一次调用FactoryBean不再缓存中 37 Object object = doGetObjectFromFactoryBean(factory, beanName); //从FactoryBean里生成 38 if (object != null &&shouldPostProcess) {39 try{40 object = postProcessObjectFromFactoryBean(object, beanName); //后置处理 41 } catch(Throwable ex) {42 throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);43 }44 }45 returnobject;46 }47 }
对比它的父类里的一些map....
factoryBeanObjectCache里存的是BeanFactory的getObject返回的对象.
singletonObjects里存一般的单例和BeanFactory对象.
然后不管是BeanFactory还是BeanFactory返回的对象.beanname都是不带&,这点和使用BeanFactory的getBean方法不太一样...等看到后面的BF可能就清楚为什么了.
另外postProcessObjectFromFactoryBean这个方法在当前类里仅仅返回传入参数object.但是是个protected的方法,子类肯定会去重写的.这个方法不出意外应该就是BeanPostProcessor参与Spring声明周期的地方(对于FactoryBean来说).
一个小测试:
1 packagespring.bf;2 3 importorg.junit.Test;4 importorg.junit.runner.RunWith;5 importorg.springframework.beans.BeansException;6 importorg.springframework.beans.factory.FactoryBean;7 importorg.springframework.beans.factory.annotation.Autowired;8 importorg.springframework.beans.factory.annotation.Qualifier;9 importorg.springframework.beans.factory.config.BeanPostProcessor;10 importorg.springframework.stereotype.Component;11 importorg.springframework.test.context.ContextConfiguration;12 importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;13 14 @RunWith(SpringJUnit4ClassRunner.class)15 @ContextConfiguration("classpath:test-application-context.xml")16 public classFactoryBeanRegistrySupportTest {17 18 @Autowired19 @Qualifier("factoryBeanRegistrySupportTest_FactoryBean")20 Object o;21 22 /** 23 * 测试BeanFactory和BeanPostProcessor24 */ 25 @Test26 public voidtest1() {27 System.out.println(o);28 }29 }30 31 32 @Component33 class FactoryBeanRegistrySupportTest_FactoryBean implements FactoryBean<Object>{34 35 private Object a = newObject();36 37 @Override38 public Object getObject() throwsException {39 returna;40 }41 42 @Override43 public Class<?>getObjectType() {44 return Object.class;45 }46 47 @Override48 public booleanisSingleton() {49 return true;50 }51 }52 53 @Component54 class FactoryBeanRegistrySupportTest_PostProcess implementsBeanPostProcessor {55 56 private static final String name = "factoryBeanRegistrySupportTest_FactoryBean";57 58 @Override59 public Object postProcessBeforeInitialization(Object bean, String beanName) throwsBeansException {60 if(beanName.equals(name)) {61 System.out.println("postProcessBeforeInitialization ->" +beanName);62 }63 returnbean;64 }65 66 @Override67 public Object postProcessAfterInitialization(Object bean, String beanName) throwsBeansException {68 if(beanName.equals(name)) {69 System.out.println("postProcessAfterInitialization ->" +beanName);70 }71 returnbean;72 }73 }
输出:
postProcessBeforeInitialization ->factoryBeanRegistrySupportTest_FactoryBean 这个是FactoryBean作为单例被new的时候做的
postProcessAfterInitialization ->factoryBeanRegistrySupportTest_FactoryBean 这个是FactoryBean作为单例被new的时候做的
postProcessAfterInitialization ->factoryBeanRegistrySupportTest_FactoryBean 这个是FactoryBean的getObject返回的对象做的
java.lang.Object@f1e3986 输出getObject返回的对象
那么为什么FactoryBean的返回对象不要做postProcessBeforeInitialization,只做了postProcessAfterInitialization 呢??? 为什么这样设定??? 不太懂.
我觉得.可能是其他bean的afterProperties可能会扫描一些特性的bean做处理..这里工厂返回的bean肯定没有被之前扫描到.而postProcessBeforeInitialization是要在afterProperties之前做的(对于单个bean来说).所以这里不再执行.
AbstractBeanFactory


1 /* 2 * Copyright 2002-2015 the original author or authors.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *http://www.apache.org/licenses/LICENSE-2.0 9 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */ 16 17 packageorg.springframework.beans.factory.support;18 19 import org.springframework.beans.*;20 import org.springframework.beans.factory.*;21 import org.springframework.beans.factory.config.*;22 importorg.springframework.core.DecoratingClassLoader;23 importorg.springframework.core.NamedThreadLocal;24 importorg.springframework.core.convert.ConversionService;25 import org.springframework.util.*;26 27 importjava.beans.PropertyEditor;28 import java.security.*;29 import java.util.*;30 importjava.util.concurrent.ConcurrentHashMap;31 32 /** 33 * Abstract base class for {@linkorg.springframework.beans.factory.BeanFactory}34 * implementations, providing the full capabilities of the35 * {@linkorg.springframework.beans.factory.config.ConfigurableBeanFactory} SPI.36 * Does <i>not</i> assume a listable bean factory: can therefore also be used37 * as base class for bean factory implementations which obtain bean definitions38 * from some backend resource (where bean definition access is an expensive operation).39 * <p>40 * <p>This class provides a singleton cache (through its base class41 * {@linkorg.springframework.beans.factory.support.DefaultSingletonBeanRegistry},42 * singleton/prototype determination, {@linkorg.springframework.beans.factory.FactoryBean}43 * handling, aliases, bean definition merging for child bean definitions,44 * and bean destruction ({@linkorg.springframework.beans.factory.DisposableBean}45 * interface, custom destroy methods). Furthermore, it can manage a bean factory46 * hierarchy (delegating to the parent in case of an unknown bean), through implementing47 * the {@linkorg.springframework.beans.factory.HierarchicalBeanFactory} interface.48 * <p>49 * <p>The main template methods to be implemented by subclasses are50 * {@link#getBeanDefinition} and {@link#createBean}, retrieving a bean definition51 * for a given bean name and creating a bean instance for a given bean definition,52 * respectively. Default implementations of those operations can be found in53 * {@linkDefaultListableBeanFactory} and {@linkAbstractAutowireCapableBeanFactory}.54 *55 *@authorRod Johnson56 *@authorJuergen Hoeller57 *@authorCostin Leau58 *@authorChris Beams59 *@see#getBeanDefinition60 *@see#createBean61 *@seeAbstractAutowireCapableBeanFactory#createBean62 *@seeDefaultListableBeanFactory#getBeanDefinition63 *@since15 April 200164 */ 65 public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implementsConfigurableBeanFactory {66 67 /** 68 * Parent bean factory, for bean inheritance support69 */ 70 privateBeanFactory parentBeanFactory;71 72 /** 73 * ClassLoader to resolve bean class names with, if necessary74 */ 75 private ClassLoader beanClassLoader =ClassUtils.getDefaultClassLoader();76 77 /** 78 * ClassLoader to temporarily resolve bean class names with, if necessary79 */ 80 privateClassLoader tempClassLoader;81 82 /** 83 * Whether to cache bean metadata or rather reobtain it for every access84 */ 85 private boolean cacheBeanMetadata = true;86 87 /** 88 * Resolution strategy for expressions in bean definition values89 */ 90 privateBeanExpressionResolver beanExpressionResolver;91 92 /** 93 * Spring ConversionService to use instead of PropertyEditors94 */ 95 privateConversionService conversionService;96 97 /** 98 * Custom PropertyEditorRegistrars to apply to the beans of this factory99 */ 100 private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = 101 new LinkedHashSet<PropertyEditorRegistrar>(4);102 103 /** 104 * A custom TypeConverter to use, overriding the default PropertyEditor mechanism105 */ 106 privateTypeConverter typeConverter;107 108 /** 109 * Custom PropertyEditors to apply to the beans of this factory110 */ 111 private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = 112 new HashMap<Class<?>, Class<? extends PropertyEditor>>(4);113 114 /** 115 * String resolvers to apply e.g. to annotation attribute values116 */ 117 private final List<StringValueResolver> embeddedValueResolvers = new LinkedList<StringValueResolver>();118 119 /** 120 * BeanPostProcessors to apply in createBean121 */ 122 private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();123 124 /** 125 * Indicates whether any InstantiationAwareBeanPostProcessors have been registered126 */ 127 private booleanhasInstantiationAwareBeanPostProcessors;128 129 /** 130 * Indicates whether any DestructionAwareBeanPostProcessors have been registered131 */ 132 private booleanhasDestructionAwareBeanPostProcessors;133 134 /** 135 * Map from scope identifier String to corresponding Scope136 */ 137 private final Map<String, Scope> scopes = new LinkedHashMap<String, Scope>(8);138 139 /** 140 * Security context used when running with a SecurityManager141 */ 142 privateSecurityContextProvider securityContextProvider;143 144 /** 145 * Map from bean name to merged RootBeanDefinition146 */ 147 private final Map<String, RootBeanDefinition> mergedBeanDefinitions = 148 new ConcurrentHashMap<String, RootBeanDefinition>(64);149 150 /** 151 * Names of beans that have already been created at least once152 */ 153 private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(64));154 155 /** 156 * Names of beans that are currently in creation157 */ 158 private final ThreadLocal<Object> prototypesCurrentlyInCreation = 159 new NamedThreadLocal<Object>("Prototype beans currently in creation");160 161 162 /** 163 * Create a new AbstractBeanFactory.164 */ 165 publicAbstractBeanFactory() {166 }167 168 /** 169 * Create a new AbstractBeanFactory with the given parent.170 *171 *@paramparentBeanFactory parent bean factory, or {@codenull} if none172 *@see#getBean173 */ 174 publicAbstractBeanFactory(BeanFactory parentBeanFactory) {175 this.parentBeanFactory =parentBeanFactory;176 }177 178 179 //---------------------------------------------------------------------180 //Implementation of BeanFactory interface181 //--------------------------------------------------------------------- 182 183 @Override184 public Object getBean(String name) throwsBeansException {185 return doGetBean(name, null, null, false);186 }187 188 @Override189 public <T> T getBean(String name, Class<T> requiredType) throwsBeansException {190 return doGetBean(name, requiredType, null, false);191 }192 193 @Override194 public Object getBean(String name, Object... args) throwsBeansException {195 return doGetBean(name, null, args, false);196 }197 198 /** 199 * Return an instance, which may be shared or independent, of the specified bean.200 *201 *@paramname the name of the bean to retrieve202 *@paramrequiredType the required type of the bean to retrieve203 *@paramargs arguments to use when creating a bean instance using explicit arguments204 * (only applied when creating a new instance as opposed to retrieving an existing one)205 *@returnan instance of the bean206 *@throwsBeansException if the bean could not be created207 */ 208 public <T> T getBean(String name, Class<T> requiredType, Object... args) throwsBeansException {209 return doGetBean(name, requiredType, args, false);210 }211 212 /** 213 * Return an instance, which may be shared or independent, of the specified bean.214 *215 *@paramname the name of the bean to retrieve216 *@paramrequiredType the required type of the bean to retrieve217 *@paramargs arguments to use when creating a bean instance using explicit arguments218 * (only applied when creating a new instance as opposed to retrieving an existing one)219 *@paramtypeCheckOnly whether the instance is obtained for a type check,220 * not for actual use221 *@returnan instance of the bean222 *@throwsBeansException if the bean could not be created223 */ 224 @SuppressWarnings("unchecked")225 protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throwsBeansException {226 227 //别名转化成bean的名字,同时有&的话直接去掉 228 final String beanName =transformedBeanName(name);229 Object bean;230 231 //Eagerly check singleton cache for manually registered singletons.232 //可能会是FactoryBean 233 Object sharedInstance =getSingleton(beanName);234 if (sharedInstance != null && args == null) {235 if(logger.isDebugEnabled()) {236 if(isSingletonCurrentlyInCreation(beanName)) {237 logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + 238 "' that is not fully initialized yet - a consequence of a circular reference");239 } else{240 logger.debug("Returning cached instance of singleton bean '" + beanName + "'");241 }242 }243 //如果是FactoryBean就调用getObject,否则就返回那个bean 244 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);245 } else { //有可能是prototype bean246 //Fail if we're already creating this bean instance:247 //We're assumably within a circular reference.248 //如果当前线程已经在创建个bean了.就抛出异常 249 if(isPrototypeCurrentlyInCreation(beanName)) {250 throw newBeanCurrentlyInCreationException(beanName);251 }252 253 //Check if bean definition exists in this factory. 254 BeanFactory parentBeanFactory =getParentBeanFactory();255 //如果这个bean的配置定义在父BF中的,即当前BF没有这个bean的配置信息 256 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {257 //Not found -> check parent.258 //转化别名成bean的实际名字,但是不会去掉& 259 String nameToLookup =originalBeanName(name);260 //调用父BF的getBean方法去获取bean. 261 if (args != null) {262 //Delegation to parent with explicit args. 263 return(T) parentBeanFactory.getBean(nameToLookup, args);264 } else{265 //No args -> delegate to standard getBean method. 266 returnparentBeanFactory.getBean(nameToLookup, requiredType);267 }268 }269 270 if (!typeCheckOnly) {271 //标记这个bean已被创建 272 markBeanAsCreated(beanName);273 }274 275 try{276 //获取BeanDefinition 277 final RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);278 //检测这个bean是不是abstract的 279 checkMergedBeanDefinition(mbd, beanName, args);280 281 //Guarantee initialization of beans that the current bean depends on.282 //A中有B,C,dependsOn=B,C 283 String[] dependsOn =mbd.getDependsOn();284 if (dependsOn != null) {285 for (String dependsOnBean : dependsOn) { //B和C286 //如果dependsOnBean中有beanName域.而mbd.getDependsOn();说明beanName中有dependsOnBean,所以是相互依赖 287 if (isDependent(beanName, dependsOnBean)) { //为true说明B,C中也有A,而外层的mbd.getDependsOn();说明A中有B,C,所以循环引用 288 throw newBeanCreationException(mbd.getResourceDescription(), beanName,289 "Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");290 }291 //beanName中有dependsOnBean,beanName依赖于dependsOnBean 292 registerDependentBean(dependsOnBean, beanName);293 //先初始化成员域的bean 294 getBean(dependsOnBean);295 }296 }297 298 //Create bean instance.299 //如果是单例 300 if(mbd.isSingleton()) {301 //获取这个bean,没创建就创建 302 sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {303 @Override304 public Object getObject() throwsBeansException {305 try{306 returncreateBean(beanName, mbd, args);307 } catch(BeansException ex) {308 //Explicitly remove instance from singleton cache: It might have been put there309 //eagerly by the creation process, to allow for circular reference resolution.310 //Also remove any beans that received a temporary reference to the bean. 311 destroySingleton(beanName);312 throwex;313 }314 }315 });316 //如果是FactoryBean就调用getObject,否则就返回那个bean 317 bean =getObjectForBeanInstance(sharedInstance, name, beanName, mbd);318 } else if (mbd.isPrototype()) { //如果是原型bean319 //It's a prototype -> create a new instance. 320 Object prototypeInstance = null;321 try{322 //记录正在创建的原型bean,这个bean和线程绑定 323 beforePrototypeCreation(beanName);324 prototypeInstance =createBean(beanName, mbd, args);325 } finally{326 //创建完毕,移除这个标记 327 afterPrototypeCreation(beanName);328 }329 //如果是FactoryBean就调用getObject,否则就返回那个bean 330 bean =getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);331 } else{332 //既不是单例又不是原型 333 String scopeName =mbd.getScope();334 final Scope scope = this.scopes.get(scopeName);335 if (scope == null) {336 throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'");337 }338 try{339 Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {340 @Override341 public Object getObject() throwsBeansException {342 beforePrototypeCreation(beanName);343 try{344 returncreateBean(beanName, mbd, args);345 } finally{346 afterPrototypeCreation(beanName);347 }348 }349 });350 bean =getObjectForBeanInstance(scopedInstance, name, beanName, mbd);351 } catch(IllegalStateException ex) {352 throw newBeanCreationException(beanName,353 "Scope '" + scopeName + "' is not active for the current thread; " + 354 "consider defining a scoped proxy for this bean if you intend to refer to it from a singleton",355 ex);356 }357 }358 } catch(BeansException ex) {359 //创建出错.360 //因为之前调用过markBeanAsCreated(beanName);标记过bean被创建,实际是失败的,所以要移除这个标记 361 cleanupAfterBeanCreationFailure(beanName);362 throwex;363 }364 }365 366 //Check if required type matches the type of the actual bean instance.367 //讲前面得到的bean进行类型转化并返回 368 if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {369 try{370 returngetTypeConverter().convertIfNecessary(bean, requiredType);371 } catch(TypeMismatchException ex) {372 if(logger.isDebugEnabled()) {373 logger.debug("Failed to convert bean '" + name + "' to required type [" + 374 ClassUtils.getQualifiedName(requiredType) + "]", ex);375 }376 throw newBeanNotOfRequiredTypeException(name, requiredType, bean.getClass());377 }378 }379 return(T) bean;380 }381 382 @Override383 public booleancontainsBean(String name) {384 String beanName =transformedBeanName(name);385 if (containsSingleton(beanName) ||containsBeanDefinition(beanName)) {386 //&开头或者是FactoryBean的实例 387 return (!BeanFactoryUtils.isFactoryDereference(name) ||isFactoryBean(name));388 }389 //Not found -> check parent.390 //本BF找不到就找父类的 391 BeanFactory parentBeanFactory =getParentBeanFactory();392 return (parentBeanFactory != null &&parentBeanFactory.containsBean(originalBeanName(name)));393 }394 395 @Override396 public boolean isSingleton(String name) throwsNoSuchBeanDefinitionException {397 String beanName = transformedBeanName(name); //去掉&并且将alias转化成真正的beanname 398 399 Object beanInstance = getSingleton(beanName, false); //取到singleton 400 if (beanInstance != null) {401 if (beanInstance instanceof FactoryBean) { //如果bean是FactoryBean.402 //&开头为true(取工厂bean)或者FactoryBean的isSingleton返回为true(不是&开头,取工厂的getObject返回) 403 return (BeanFactoryUtils.isFactoryDereference(name) || ((FactoryBean<?>) beanInstance).isSingleton());404 } else { //不是工厂bean的情况下,不是&开头返回ture,就是最一般的单例bean. 405 return !BeanFactoryUtils.isFactoryDereference(name);406 }407 } else if (containsSingleton(beanName)) { //不知道什么时候会进,getSingleton,但是containsSingleton为true.可能是abstract的bean吧 408 return true;409 } else{410 //No singleton instance found -> check bean definition. 411 BeanFactory parentBeanFactory =getParentBeanFactory();412 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {413 //No bean definition found in this factory -> delegate to parent.414 //本BF没有这个bean的定义的话可以去找父类的. 415 returnparentBeanFactory.isSingleton(originalBeanName(name));416 }417 418 //合并父类和本身的bean定义 419 RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);420 421 //In case of FactoryBean, return singleton status of created object if not a dereference. 422 if (mbd.isSingleton()) { //定义中是单例,在判断是不是工厂 423 if (isFactoryBean(beanName, mbd)) { //是工厂的话并且是不带&的话需要调用工厂的isSingleton方法 424 if(BeanFactoryUtils.isFactoryDereference(name)) {425 return true;426 }427 FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX +beanName);428 returnfactoryBean.isSingleton();429 } else { //不是工厂bean就是true 430 return !BeanFactoryUtils.isFactoryDereference(name);431 }432 } else{433 return false;434 }435 }436 }437 438 @Override439 public boolean isPrototype(String name) throwsNoSuchBeanDefinitionException {440 String beanName =transformedBeanName(name);441 442 BeanFactory parentBeanFactory =getParentBeanFactory();443 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {444 //No bean definition found in this factory -> delegate to parent.445 //本BF中没有这个bean的定义就找父工厂 446 returnparentBeanFactory.isPrototype(originalBeanName(name));447 }448 449 //合并父BF和本BF得到bean的定义 450 RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);451 if (mbd.isPrototype()) { //bean的定义是原型,并且取不带&的bean,那就是原型对象为true,如果取&的bean,那需要返回的是工厂,如果是FactoryBean452 //In case of FactoryBean, return singleton status of created object if not a dereference. 453 return (!BeanFactoryUtils.isFactoryDereference(name) ||isFactoryBean(beanName, mbd));454 } else{455 //Singleton or scoped - not a prototype.456 //However, FactoryBean may still produce a prototype object...457 //如果是&开头取工厂就直接返回false 458 if(BeanFactoryUtils.isFactoryDereference(name)) {459 return false;460 }461 //不是&开头的话要看工厂的isSingleton或者isPrototype 462 if(isFactoryBean(beanName, mbd)) {463 final FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX +beanName);464 if (System.getSecurityManager() != null) {465 return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {466 @Override467 publicBoolean run() {468 return ((factoryBean instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factoryBean).isPrototype()) || 469 !factoryBean.isSingleton());470 }471 }, getAccessControlContext());472 } else{473 return ((factoryBean instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factoryBean).isPrototype()) || 474 !factoryBean.isSingleton());475 }476 } else{477 return false;478 }479 }480 }481 482 @Override483 public boolean isTypeMatch(String name, Class<?> targetType) throwsNoSuchBeanDefinitionException {484 String beanName =transformedBeanName(name);485 Class<?> typeToMatch = (targetType != null ? targetType : Object.class);486 487 //Check manually registered singletons. 488 Object beanInstance = getSingleton(beanName, false);489 if (beanInstance != null) {490 if (beanInstance instanceofFactoryBean) {491 if (!BeanFactoryUtils.isFactoryDereference(name)) { //取工厂的返回 492 Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance);493 return (type != null &&ClassUtils.isAssignable(typeToMatch, type));494 } else { //取工厂bean 495 returnClassUtils.isAssignableValue(typeToMatch, beanInstance);496 }497 } else { //取一般的bean 498 return !BeanFactoryUtils.isFactoryDereference(name) && 499 ClassUtils.isAssignableValue(typeToMatch, beanInstance);500 }501 } else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {502 //null instance registered 503 return false;504 } else{505 //No singleton instance found -> check bean definition. 506 BeanFactory parentBeanFactory =getParentBeanFactory();507 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {508 //No bean definition found in this factory -> delegate to parent. 509 returnparentBeanFactory.isTypeMatch(originalBeanName(name), targetType);510 }511 512 //Retrieve corresponding bean definition. 513 RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);514 515 Class<?>[] typesToMatch = (FactoryBean.class.equals(typeToMatch) ? 516 new Class<?>[]{typeToMatch} : new Class<?>[]{FactoryBean.class, typeToMatch});517 518 //Check decorated bean definition, if any: We assume it'll be easier519 //to determine the decorated bean's type than the proxy's type. 520 BeanDefinitionHolder dbd =mbd.getDecoratedDefinition();521 if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {522 RootBeanDefinition tbd =getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);523 Class<?> targetClass =predictBeanType(dbd.getBeanName(), tbd, typesToMatch);524 if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {525 returntypeToMatch.isAssignableFrom(targetClass);526 }527 }528 529 Class<?> beanType =predictBeanType(beanName, mbd, typesToMatch);530 if (beanType == null) {531 return false;532 }533 534 //Check bean class whether we're dealing with a FactoryBean. 535 if (FactoryBean.class.isAssignableFrom(beanType)) {536 if (!BeanFactoryUtils.isFactoryDereference(name)) {537 //If it's a FactoryBean, we want to look at what it creates, not the factory class. 538 beanType =getTypeForFactoryBean(beanName, mbd);539 if (beanType == null) {540 return false;541 }542 }543 } else if(BeanFactoryUtils.isFactoryDereference(name)) {544 //Special case: A SmartInstantiationAwareBeanPostProcessor returned a non-FactoryBean545 //type but we nevertheless are being asked to dereference a FactoryBean...546 //Let's check the original bean class and proceed with it if it is a FactoryBean. 547 beanType = predictBeanType(beanName, mbd, FactoryBean.class);548 if (beanType == null || !FactoryBean.class.isAssignableFrom(beanType)) {549 return false;550 }551 }552 553 returntypeToMatch.isAssignableFrom(beanType);554 }555 }556 557 @Override558 public Class<?> getType(String name) throwsNoSuchBeanDefinitionException {559 String beanName =transformedBeanName(name);560 561 //Check manually registered singletons. 562 Object beanInstance = getSingleton(beanName, false);563 if (beanInstance != null) {564 if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {565 return getTypeForFactoryBean((FactoryBean<?>) beanInstance);566 } else{567 returnbeanInstance.getClass();568 }569 } else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {570 //null instance registered 571 return null;572 } else{573 //No singleton instance found -> check bean definition. 574 BeanFactory parentBeanFactory =getParentBeanFactory();575 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {576 //No bean definition found in this factory -> delegate to parent. 577 returnparentBeanFactory.getType(originalBeanName(name));578 }579 580 RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);581 582 //Check decorated bean definition, if any: We assume it'll be easier583 //to determine the decorated bean's type than the proxy's type. 584 BeanDefinitionHolder dbd =mbd.getDecoratedDefinition();585 if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {586 RootBeanDefinition tbd =getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);587 Class<?> targetClass =predictBeanType(dbd.getBeanName(), tbd);588 if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {589 returntargetClass;590 }591 }592 593 Class<?> beanClass =predictBeanType(beanName, mbd);594 595 //Check bean class whether we're dealing with a FactoryBean. 596 if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) {597 if (!BeanFactoryUtils.isFactoryDereference(name)) {598 //If it's a FactoryBean, we want to look at what it creates, not at the factory class. 599 returngetTypeForFactoryBean(beanName, mbd);600 } else{601 returnbeanClass;602 }603 } else{604 return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null);605 }606 }607 }608 609 /** 610 * 覆盖了父类方法,增加了对FactoryBean的支持611 *612 *@paramname613 *@return 614 */ 615 @Override616 publicString[] getAliases(String name) {617 String beanName =transformedBeanName(name);618 List<String> aliases = new ArrayList<String>();619 boolean factoryPrefix =name.startsWith(FACTORY_BEAN_PREFIX);620 String fullBeanName =beanName;621 if(factoryPrefix) {622 fullBeanName = FACTORY_BEAN_PREFIX +beanName;623 }624 if (!fullBeanName.equals(name)) {625 aliases.add(fullBeanName);626 }627 String[] retrievedAliases = super.getAliases(beanName);628 for(String retrievedAlias : retrievedAliases) {629 String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") +retrievedAlias;630 if (!alias.equals(name)) {631 aliases.add(alias);632 }633 }634 if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) {635 BeanFactory parentBeanFactory =getParentBeanFactory();636 if (parentBeanFactory != null) {637 aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName)));638 }639 }640 returnStringUtils.toStringArray(aliases);641 }642 643 644 //---------------------------------------------------------------------645 //Implementation of HierarchicalBeanFactory interface646 //--------------------------------------------------------------------- 647 648 @Override649 publicBeanFactory getParentBeanFactory() {650 return this.parentBeanFactory;651 }652 653 @Override654 public booleancontainsLocalBean(String name) {655 String beanName =transformedBeanName(name);656 return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) && 657 (!BeanFactoryUtils.isFactoryDereference(name) ||isFactoryBean(beanName)));658 }659 660 661 //---------------------------------------------------------------------662 //Implementation of ConfigurableBeanFactory interface663 //--------------------------------------------------------------------- 664 665 @Override666 public voidsetParentBeanFactory(BeanFactory parentBeanFactory) {667 if (this.parentBeanFactory != null && this.parentBeanFactory !=parentBeanFactory) {668 throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory);669 }670 this.parentBeanFactory =parentBeanFactory;671 }672 673 @Override674 public voidsetBeanClassLoader(ClassLoader beanClassLoader) {675 this.beanClassLoader = (beanClassLoader != null ?beanClassLoader : ClassUtils.getDefaultClassLoader());676 }677 678 @Override679 publicClassLoader getBeanClassLoader() {680 return this.beanClassLoader;681 }682 683 @Override684 public voidsetTempClassLoader(ClassLoader tempClassLoader) {685 this.tempClassLoader =tempClassLoader;686 }687 688 @Override689 publicClassLoader getTempClassLoader() {690 return this.tempClassLoader;691 }692 693 @Override694 public void setCacheBeanMetadata(booleancacheBeanMetadata) {695 this.cacheBeanMetadata =cacheBeanMetadata;696 }697 698 @Override699 public booleanisCacheBeanMetadata() {700 return this.cacheBeanMetadata;701 }702 703 @Override704 public voidsetBeanExpressionResolver(BeanExpressionResolver resolver) {705 this.beanExpressionResolver =resolver;706 }707 708 @Override709 publicBeanExpressionResolver getBeanExpressionResolver() {710 return this.beanExpressionResolver;711 }712 713 @Override714 public voidsetConversionService(ConversionService conversionService) {715 this.conversionService =conversionService;716 }717 718 @Override719 publicConversionService getConversionService() {720 return this.conversionService;721 }722 723 @Override724 public voidaddPropertyEditorRegistrar(PropertyEditorRegistrar registrar) {725 Assert.notNull(registrar, "PropertyEditorRegistrar must not be null");726 this.propertyEditorRegistrars.add(registrar);727 }728 729 /** 730 * Return the set of PropertyEditorRegistrars.731 */ 732 public Set<PropertyEditorRegistrar>getPropertyEditorRegistrars() {733 return this.propertyEditorRegistrars;734 }735 736 @Override737 public void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor>propertyEditorClass) {738 Assert.notNull(requiredType, "Required type must not be null");739 Assert.isAssignable(PropertyEditor.class, propertyEditorClass);740 this.customEditors.put(requiredType, propertyEditorClass);741 }742 743 @Override744 public voidcopyRegisteredEditorsTo(PropertyEditorRegistry registry) {745 registerCustomEditors(registry);746 }747 748 /** 749 * Return the map of custom editors, with Classes as keys and PropertyEditor classes as values.750 */ 751 public Map<Class<?>, Class<? extends PropertyEditor>>getCustomEditors() {752 return this.customEditors;753 }754 755 @Override756 public voidsetTypeConverter(TypeConverter typeConverter) {757 this.typeConverter =typeConverter;758 }759 760 /** 761 * Return the custom TypeConverter to use, if any.762 *763 *@returnthe custom TypeConverter, or {@codenull} if none specified764 */ 765 protectedTypeConverter getCustomTypeConverter() {766 return this.typeConverter;767 }768 769 @Override770 publicTypeConverter getTypeConverter() {771 TypeConverter customConverter =getCustomTypeConverter();772 if (customConverter != null) {773 returncustomConverter;774 } else{775 //Build default TypeConverter, registering custom editors. 776 SimpleTypeConverter typeConverter = newSimpleTypeConverter();777 typeConverter.setConversionService(getConversionService());778 registerCustomEditors(typeConverter);779 returntypeConverter;780 }781 }782 783 @Override784 public voidaddEmbeddedValueResolver(StringValueResolver valueResolver) {785 Assert.notNull(valueResolver, "StringValueResolver must not be null");786 this.embeddedValueResolvers.add(valueResolver);787 }788 789 @Override790 publicString resolveEmbeddedValue(String value) {791 String result =value;792 for (StringValueResolver resolver : this.embeddedValueResolvers) {793 if (result == null) {794 return null;795 }796 result =resolver.resolveStringValue(result);797 }798 returnresult;799 }800 801 @Override802 public voidaddBeanPostProcessor(BeanPostProcessor beanPostProcessor) {803 Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");804 this.beanPostProcessors.remove(beanPostProcessor);805 this.beanPostProcessors.add(beanPostProcessor);806 if (beanPostProcessor instanceofInstantiationAwareBeanPostProcessor) {807 this.hasInstantiationAwareBeanPostProcessors = true;808 }809 if (beanPostProcessor instanceofDestructionAwareBeanPostProcessor) {810 this.hasDestructionAwareBeanPostProcessors = true;811 }812 }813 814 @Override815 public intgetBeanPostProcessorCount() {816 return this.beanPostProcessors.size();817 }818 819 /** 820 * Return the list of BeanPostProcessors that will get applied821 * to beans created with this factory.822 */ 823 public List<BeanPostProcessor>getBeanPostProcessors() {824 return this.beanPostProcessors;825 }826 827 /** 828 * Return whether this factory holds a InstantiationAwareBeanPostProcessor829 * that will get applied to singleton beans on shutdown.830 *831 *@see#addBeanPostProcessor832 *@seeorg.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor833 */ 834 protected booleanhasInstantiationAwareBeanPostProcessors() {835 return this.hasInstantiationAwareBeanPostProcessors;836 }837 838 /** 839 * Return whether this factory holds a DestructionAwareBeanPostProcessor840 * that will get applied to singleton beans on shutdown.841 *842 *@see#addBeanPostProcessor843 *@seeorg.springframework.beans.factory.config.DestructionAwareBeanPostProcessor844 */ 845 protected booleanhasDestructionAwareBeanPostProcessors() {846 return this.hasDestructionAwareBeanPostProcessors;847 }848 849 @Override850 public voidregisterScope(String scopeName, Scope scope) {851 Assert.notNull(scopeName, "Scope identifier must not be null");852 Assert.notNull(scope, "Scope must not be null");853 if (SCOPE_SINGLETON.equals(scopeName) ||SCOPE_PROTOTYPE.equals(scopeName)) {854 throw new IllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'");855 }856 Scope previous = this.scopes.put(scopeName, scope);857 if (previous != null && previous !=scope) {858 if(logger.isInfoEnabled()) {859 logger.info("Replacing scope '" + scopeName + "' from [" + previous + "] to [" + scope + "]");860 }861 } else{862 if(logger.isDebugEnabled()) {863 logger.debug("Registering scope '" + scopeName + "' with implementation [" + scope + "]");864 }865 }866 }867 868 @Override869 publicString[] getRegisteredScopeNames() {870 return StringUtils.toStringArray(this.scopes.keySet());871 }872 873 @Override874 publicScope getRegisteredScope(String scopeName) {875 Assert.notNull(scopeName, "Scope identifier must not be null");876 return this.scopes.get(scopeName);877 }878 879 /** 880 * Set the security context provider for this bean factory. If a security manager881 * is set, interaction with the user code will be executed using the privileged882 * of the provided security context.883 */ 884 public voidsetSecurityContextProvider(SecurityContextProvider securityProvider) {885 this.securityContextProvider =securityProvider;886 }887 888 /** 889 * Delegate the creation of the access control context to the890 * {@link#setSecurityContextProvider SecurityContextProvider}.891 */ 892 @Override893 publicAccessControlContext getAccessControlContext() {894 return (this.securityContextProvider != null ? 895 this.securityContextProvider.getAccessControlContext() :896 AccessController.getContext());897 }898 899 @Override900 public voidcopyConfigurationFrom(ConfigurableBeanFactory otherFactory) {901 Assert.notNull(otherFactory, "BeanFactory must not be null");902 setBeanClassLoader(otherFactory.getBeanClassLoader());903 setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());904 setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());905 if (otherFactory instanceofAbstractBeanFactory) {906 AbstractBeanFactory otherAbstractFactory =(AbstractBeanFactory) otherFactory;907 this.customEditors.putAll(otherAbstractFactory.customEditors);908 this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars);909 this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors);910 this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors || 911 otherAbstractFactory.hasInstantiationAwareBeanPostProcessors;912 this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors || 913 otherAbstractFactory.hasDestructionAwareBeanPostProcessors;914 this.scopes.putAll(otherAbstractFactory.scopes);915 this.securityContextProvider =otherAbstractFactory.securityContextProvider;916 } else{917 setTypeConverter(otherFactory.getTypeConverter());918 }919 }920 921 /** 922 * Return a 'merged' BeanDefinition for the given bean name,923 * merging a child bean definition with its parent if necessary.924 * <p>This {@codegetMergedBeanDefinition} considers bean definition925 * in ancestors as well.926 *927 *@paramname the name of the bean to retrieve the merged definition for928 * (may be an alias)929 *@returna (potentially merged) RootBeanDefinition for the given bean930 *@throwsNoSuchBeanDefinitionException if there is no bean with the given name931 *@throwsBeanDefinitionStoreException in case of an invalid bean definition932 */ 933 @Override934 public BeanDefinition getMergedBeanDefinition(String name) throwsBeansException {935 String beanName =transformedBeanName(name);936 937 //Efficiently check whether bean definition exists in this factory. 938 if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceofConfigurableBeanFactory) {939 return((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(beanName);940 }941 //Resolve merged bean definition locally. 942 returngetMergedLocalBeanDefinition(beanName);943 }944 945 @Override946 public boolean isFactoryBean(String name) throwsNoSuchBeanDefinitionException {947 String beanName =transformedBeanName(name);948 949 Object beanInstance = getSingleton(beanName, false);950 if (beanInstance != null) {951 return (beanInstance instanceofFactoryBean);952 } else if(containsSingleton(beanName)) {953 //可能这个bean不允许被创建(abstract的bean)?954 //null instance registered 955 return false;956 }957 958 //No singleton instance found -> check bean definition. 959 if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceofConfigurableBeanFactory) {960 //No bean definition found in this factory -> delegate to parent.961 //本BF没有就找父类的 962 return((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);963 }964 965 returnisFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));966 }967 968 @Override969 public booleanisActuallyInCreation(String beanName) {970 return (isSingletonCurrentlyInCreation(beanName) ||isPrototypeCurrentlyInCreation(beanName));971 }972 973 /** 974 * Return whether the specified prototype bean is currently in creation975 * (within the current thread).976 *977 *@parambeanName the name of the bean978 */ 979 protected booleanisPrototypeCurrentlyInCreation(String beanName) {980 Object curVal = this.prototypesCurrentlyInCreation.get();981 return (curVal != null && 982 (curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));983 }984 985 /** 986 * Callback before prototype creation.987 * 将正在创建的额原型bean放到threadlocal中,1个原型bean的类在1个线程中只能有1个正在创建的实例988 * <p>The default implementation register the prototype as currently in creation.989 *990 *@parambeanName the name of the prototype about to be created991 *@see#isPrototypeCurrentlyInCreation992 */ 993 @SuppressWarnings("unchecked")994 protected voidbeforePrototypeCreation(String beanName) {995 Object curVal = this.prototypesCurrentlyInCreation.get();996 if (curVal == null) {997 this.prototypesCurrentlyInCreation.set(beanName);998 } else if (curVal instanceofString) {999 Set<String> beanNameSet = new HashSet<String>(2);1000 beanNameSet.add((String) curVal);1001 beanNameSet.add(beanName);1002 this.prototypesCurrentlyInCreation.set(beanNameSet);1003 } else{1004 Set<String> beanNameSet = (Set<String>) curVal;1005 beanNameSet.add(beanName);1006 }1007 }1008 1009 /** 1010 * Callback after prototype creation.1011 * 将之前线程变量中存着的正在创建的原型bean移除,因为已经创建完毕1012 * <p>The default implementation marks the prototype as not in creation anymore.1013 *1014 *@parambeanName the name of the prototype that has been created1015 *@see#isPrototypeCurrentlyInCreation1016 */ 1017 @SuppressWarnings("unchecked")1018 protected voidafterPrototypeCreation(String beanName) {1019 Object curVal = this.prototypesCurrentlyInCreation.get();1020 if (curVal instanceofString) {1021 this.prototypesCurrentlyInCreation.remove();1022 } else if (curVal instanceofSet) {1023 Set<String> beanNameSet = (Set<String>) curVal;1024 beanNameSet.remove(beanName);1025 if(beanNameSet.isEmpty()) {1026 this.prototypesCurrentlyInCreation.remove();1027 }1028 }1029 }1030 1031 @Override1032 public voiddestroyBean(String beanName, Object beanInstance) {1033 destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName));1034 }1035 1036 /** 1037 * Destroy the given bean instance (usually a prototype instance1038 * obtained from this factory) according to the given bean definition.1039 *1040 *@parambeanName the name of the bean definition1041 *@parambeanInstance the bean instance to destroy1042 *@parammbd the merged bean definition1043 */ 1044 protected voiddestroyBean(String beanName, Object beanInstance, RootBeanDefinition mbd) {1045 newDisposableBeanAdapter(beanInstance, beanName, mbd, getBeanPostProcessors(), getAccessControlContext()).destroy();1046 }1047 1048 @Override1049 public voiddestroyScopedBean(String beanName) {1050 RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);1051 if (mbd.isSingleton() ||mbd.isPrototype()) {1052 throw newIllegalArgumentException(1053 "Bean name '" + beanName + "' does not correspond to an object in a mutable scope");1054 }1055 String scopeName =mbd.getScope();1056 Scope scope = this.scopes.get(scopeName);1057 if (scope == null) {1058 throw new IllegalStateException("No Scope SPI registered for scope '" + scopeName + "'");1059 }1060 Object bean =scope.remove(beanName);1061 if (bean != null) {1062 destroyBean(beanName, bean, mbd);1063 }1064 }1065 1066 1067 //---------------------------------------------------------------------1068 //Implementation methods1069 //--------------------------------------------------------------------- 1070 1071 /** 1072 * Return the bean name, stripping out the factory dereference prefix if necessary,1073 * and resolving aliases to canonical names.1074 * 去掉&前缀,并且把alias->真正的beanname1075 *1076 *@paramname the user-specified name1077 *@returnthe transformed bean name1078 */ 1079 protectedString transformedBeanName(String name) {1080 returncanonicalName(BeanFactoryUtils.transformedBeanName(name));1081 }1082 1083 /** 1084 * Determine the original bean name, resolving locally defined aliases to canonical names.1085 *1086 *@paramname the user-specified name1087 *@returnthe original bean name1088 */ 1089 protectedString originalBeanName(String name) {1090 String beanName =transformedBeanName(name);1091 if(name.startsWith(FACTORY_BEAN_PREFIX)) {1092 beanName = FACTORY_BEAN_PREFIX +beanName;1093 }1094 returnbeanName;1095 }1096 1097 /** 1098 * Initialize the given BeanWrapper with the custom editors registered1099 * with this factory. To be called for BeanWrappers that will create1100 * and populate bean instances.1101 * <p>The default implementation delegates to {@link#registerCustomEditors}.1102 * Can be overridden in subclasses.1103 *1104 *@parambw the BeanWrapper to initialize1105 */ 1106 protected voidinitBeanWrapper(BeanWrapper bw) {1107 bw.setConversionService(getConversionService());1108 registerCustomEditors(bw);1109 }1110 1111 /** 1112 * Initialize the given PropertyEditorRegistry with the custom editors1113 * that have been registered with this BeanFactory.1114 * <p>To be called for BeanWrappers that will create and populate bean1115 * instances, and for SimpleTypeConverter used for constructor argument1116 * and factory method type conversion.1117 *1118 *@paramregistry the PropertyEditorRegistry to initialize1119 */ 1120 protected voidregisterCustomEditors(PropertyEditorRegistry registry) {1121 PropertyEditorRegistrySupport registrySupport = 1122 (registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);1123 if (registrySupport != null) {1124 registrySupport.useConfigValueEditors();1125 }1126 if (!this.propertyEditorRegistrars.isEmpty()) {1127 for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {1128 try{1129 registrar.registerCustomEditors(registry);1130 } catch(BeanCreationException ex) {1131 Throwable rootCause =ex.getMostSpecificCause();1132 if (rootCause instanceofBeanCurrentlyInCreationException) {1133 BeanCreationException bce =(BeanCreationException) rootCause;1134 if(isCurrentlyInCreation(bce.getBeanName())) {1135 if(logger.isDebugEnabled()) {1136 logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() + 1137 "] failed because it tried to obtain currently created bean '" + 1138 ex.getBeanName() + "': " +ex.getMessage());1139 }1140 onSuppressedException(ex);1141 continue;1142 }1143 }1144 throwex;1145 }1146 }1147 }1148 if (!this.customEditors.isEmpty()) {1149 for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : this.customEditors.entrySet()) {1150 Class<?> requiredType =entry.getKey();1151 Class<? extends PropertyEditor> editorClass =entry.getValue();1152 registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass));1153 }1154 }1155 }1156 1157 1158 /** 1159 * Return a merged RootBeanDefinition, traversing the parent bean definition1160 * if the specified bean corresponds to a child bean definition.1161 * 有缓存直接缓存取,没有的话就合并自己的和父类的.1162 *1163 *@parambeanName the name of the bean to retrieve the merged definition for1164 *@returna (potentially merged) RootBeanDefinition for the given bean1165 *@throwsNoSuchBeanDefinitionException if there is no bean with the given name1166 *@throwsBeanDefinitionStoreException in case of an invalid bean definition1167 */ 1168 protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throwsBeansException {1169 //Quick check on the concurrent map first, with minimal locking. 1170 RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);1171 if (mbd != null) {1172 returnmbd;1173 }1174 returngetMergedBeanDefinition(beanName, getBeanDefinition(beanName));1175 }1176 1177 /** 1178 * Return a RootBeanDefinition for the given top-level bean, by merging with1179 * the parent if the given bean's definition is a child bean definition.1180 *1181 *@parambeanName the name of the bean definition1182 *@parambd the original bean definition (Root/ChildBeanDefinition)1183 *@returna (potentially merged) RootBeanDefinition for the given bean1184 *@throwsBeanDefinitionStoreException in case of an invalid bean definition1185 */ 1186 protectedRootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)1187 throwsBeanDefinitionStoreException {1188 1189 return getMergedBeanDefinition(beanName, bd, null);1190 }1191 1192 /** 1193 * Return a RootBeanDefinition for the given bean, by merging with the1194 * parent if the given bean's definition is a child bean definition.1195 *1196 *@parambeanName the name of the bean definition1197 *@parambd the original bean definition (Root/ChildBeanDefinition)1198 *@paramcontainingBd the containing bean definition in case of inner bean,1199 * or {@codenull} in case of a top-level bean1200 *@returna (potentially merged) RootBeanDefinition for the given bean1201 *@throwsBeanDefinitionStoreException in case of an invalid bean definition1202 */ 1203 protectedRootBeanDefinition getMergedBeanDefinition(1204 String beanName, BeanDefinition bd, BeanDefinition containingBd)1205 throwsBeanDefinitionStoreException {1206 1207 synchronized (this.mergedBeanDefinitions) {1208 RootBeanDefinition mbd = null;1209 1210 //Check with full lock now in order to enforce the same merged instance. 1211 if (containingBd == null) {1212 mbd = this.mergedBeanDefinitions.get(beanName);1213 }1214 1215 if (mbd == null) {1216 if (bd.getParentName() == null) {1217 //Use copy of given root bean definition. 1218 if (bd instanceofRootBeanDefinition) {1219 mbd =((RootBeanDefinition) bd).cloneBeanDefinition();1220 } else{1221 mbd = newRootBeanDefinition(bd);1222 }1223 } else{1224 //Child bean definition: needs to be merged with parent. 1225 BeanDefinition pbd;1226 try{1227 String parentBeanName =transformedBeanName(bd.getParentName());1228 if (!beanName.equals(parentBeanName)) {1229 pbd =getMergedBeanDefinition(parentBeanName);1230 } else{1231 if (getParentBeanFactory() instanceofConfigurableBeanFactory) {1232 pbd =((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(parentBeanName);1233 } else{1234 throw newNoSuchBeanDefinitionException(bd.getParentName(),1235 "Parent name '" + bd.getParentName() + "' is equal to bean name '" + beanName + 1236 "': cannot be resolved without an AbstractBeanFactory parent");1237 }1238 }1239 } catch(NoSuchBeanDefinitionException ex) {1240 throw newBeanDefinitionStoreException(bd.getResourceDescription(), beanName,1241 "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);1242 }1243 //Deep copy with overridden values. 1244 mbd = newRootBeanDefinition(pbd);1245 mbd.overrideFrom(bd);1246 }1247 1248 //Set default singleton scope, if not configured before. 1249 if (!StringUtils.hasLength(mbd.getScope())) {1250 mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);1251 }1252 1253 //A bean contained in a non-singleton bean cannot be a singleton itself.1254 //Let's correct this on the fly here, since this might be the result of1255 //parent-child merging for the outer bean, in which case the original inner bean1256 //definition will not have inherited the merged outer bean's singleton status. 1257 if (containingBd != null && !containingBd.isSingleton() &&mbd.isSingleton()) {1258 mbd.setScope(containingBd.getScope());1259 }1260 1261 //Only cache the merged bean definition if we're already about to create an1262 //instance of the bean, or at least have already created an instance before. 1263 if (containingBd == null && isCacheBeanMetadata() &&isBeanEligibleForMetadataCaching(beanName)) {1264 this.mergedBeanDefinitions.put(beanName, mbd);1265 }1266 }1267 1268 returnmbd;1269 }1270 }1271 1272 /** 1273 * Check the given merged bean definition,1274 * potentially throwing validation exceptions.1275 *1276 *@parammbd the merged bean definition to check1277 *@parambeanName the name of the bean1278 *@paramargs the arguments for bean creation, if any1279 *@throwsBeanDefinitionStoreException in case of validation failure1280 */ 1281 protected voidcheckMergedBeanDefinition(RootBeanDefinition mbd, String beanName, Object[] args)1282 throwsBeanDefinitionStoreException {1283 1284 if(mbd.isAbstract()) {1285 throw newBeanIsAbstractException(beanName);1286 }1287 }1288 1289 /** 1290 * Remove the merged bean definition for the specified bean,1291 * recreating it on next access.1292 *1293 *@parambeanName the bean name to clear the merged definition for1294 */ 1295 protected voidclearMergedBeanDefinition(String beanName) {1296 this.mergedBeanDefinitions.remove(beanName);1297 }1298 1299 /** 1300 * Resolve the bean class for the specified bean definition,1301 * resolving a bean class name into a Class reference (if necessary)1302 * and storing the resolved Class in the bean definition for further use.1303 *1304 *@parammbd the merged bean definition to determine the class for1305 *@parambeanName the name of the bean (for error handling purposes)1306 *@paramtypesToMatch the types to match in case of internal type matching purposes1307 * (also signals that the returned {@codeClass} will never be exposed to application code)1308 *@returnthe resolved bean class (or {@codenull} if none)1309 *@throwsCannotLoadBeanClassException if we failed to load the class1310 */ 1311 protected Class<?> resolveBeanClass(final RootBeanDefinition mbd, String beanName, final Class<?>... typesToMatch)1312 throwsCannotLoadBeanClassException {1313 try{1314 if(mbd.hasBeanClass()) {1315 returnmbd.getBeanClass();1316 }1317 if (System.getSecurityManager() != null) {1318 return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() {1319 @Override1320 public Class<?> run() throwsException {1321 returndoResolveBeanClass(mbd, typesToMatch);1322 }1323 }, getAccessControlContext());1324 } else{1325 returndoResolveBeanClass(mbd, typesToMatch);1326 }1327 } catch(PrivilegedActionException pae) {1328 ClassNotFoundException ex =(ClassNotFoundException) pae.getException();1329 throw newCannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);1330 } catch(ClassNotFoundException ex) {1331 throw newCannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);1332 } catch(LinkageError err) {1333 throw newCannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err);1334 }1335 }1336 1337 private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch) throwsClassNotFoundException {1338 if (!ObjectUtils.isEmpty(typesToMatch)) {1339 ClassLoader tempClassLoader =getTempClassLoader();1340 if (tempClassLoader != null) {1341 if (tempClassLoader instanceofDecoratingClassLoader) {1342 DecoratingClassLoader dcl =(DecoratingClassLoader) tempClassLoader;1343 for (Class<?>typeToMatch : typesToMatch) {1344 dcl.excludeClass(typeToMatch.getName());1345 }1346 }1347 String className =mbd.getBeanClassName();1348 return (className != null ? ClassUtils.forName(className, tempClassLoader) : null);1349 }1350 }1351 returnmbd.resolveBeanClass(getBeanClassLoader());1352 }1353 1354 /** 1355 * Evaluate the given String as contained in a bean definition,1356 * potentially resolving it as an expression.1357 *1358 *@paramvalue the value to check1359 *@parambeanDefinition the bean definition that the value comes from1360 *@returnthe resolved value1361 *@see#setBeanExpressionResolver1362 */ 1363 protectedObject evaluateBeanDefinitionString(String value, BeanDefinition beanDefinition) {1364 if (this.beanExpressionResolver == null) {1365 returnvalue;1366 }1367 Scope scope = (beanDefinition != null ? getRegisteredScope(beanDefinition.getScope()) : null);1368 return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope));1369 }1370 1371 1372 /** 1373 * Predict the eventual bean type (of the processed bean instance) for the1374 * specified bean. Called by {@link#getType} and {@link#isTypeMatch}.1375 * Does not need to handle FactoryBeans specifically, since it is only1376 * supposed to operate on the raw bean type.1377 * <p>This implementation is simplistic in that it is not able to1378 * handle factory methods and InstantiationAwareBeanPostProcessors.1379 * It only predicts the bean type correctly for a standard bean.1380 * To be overridden in subclasses, applying more sophisticated type detection.1381 *1382 *@parambeanName the name of the bean1383 *@parammbd the merged bean definition to determine the type for1384 *@paramtypesToMatch the types to match in case of internal type matching purposes1385 * (also signals that the returned {@codeClass} will never be exposed to application code)1386 *@returnthe type of the bean, or {@codenull} if not predictable1387 */ 1388 protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {1389 if (mbd.getFactoryMethodName() != null) {1390 return null;1391 }1392 returnresolveBeanClass(mbd, beanName, typesToMatch);1393 }1394 1395 /** 1396 * Check whether the given bean is defined as a {@linkFactoryBean}.1397 *1398 *@parambeanName the name of the bean1399 *@parammbd the corresponding bean definition1400 */ 1401 protected booleanisFactoryBean(String beanName, RootBeanDefinition mbd) {1402 Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class);1403 return (beanType != null && FactoryBean.class.isAssignableFrom(beanType));1404 }1405 1406 /** 1407 * Determine the bean type for the given FactoryBean definition, as far as possible.1408 * Only called if there is no singleton instance registered for the target bean already.1409 * <p>The default implementation creates the FactoryBean via {@codegetBean}1410 * to call its {@codegetObjectType} method. Subclasses are encouraged to optimize1411 * this, typically by just instantiating the FactoryBean but not populating it yet,1412 * trying whether its {@codegetObjectType} method already returns a type.1413 * If no type found, a full FactoryBean creation as performed by this implementation1414 * should be used as fallback.1415 *1416 *@parambeanName the name of the bean1417 *@parammbd the merged bean definition for the bean1418 *@returnthe type for the bean if determinable, or {@codenull} else1419 *@seeorg.springframework.beans.factory.FactoryBean#getObjectType()1420 *@see#getBean(String)1421 */ 1422 protected Class<?>getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {1423 if (!mbd.isSingleton()) {1424 return null;1425 }1426 try{1427 FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);1428 returngetTypeForFactoryBean(factoryBean);1429 } catch(BeanCreationException ex) {1430 if (ex instanceofBeanCurrentlyInCreationException) {1431 if(logger.isDebugEnabled()) {1432 logger.debug("Bean currently in creation on FactoryBean type check: " +ex);1433 }1434 } else{1435 if(logger.isWarnEnabled()) {1436 logger.warn("Bean creation exception on FactoryBean type check: " +ex);1437 }1438 }1439 onSuppressedException(ex);1440 return null;1441 }1442 }1443 1444 /** 1445 * Mark the specified bean as already created (or about to be created).1446 * <p>This allows the bean factory to optimize its caching for repeated1447 * creation of the specified bean.1448 *1449 *@parambeanName the name of the bean1450 */ 1451 protected voidmarkBeanAsCreated(String beanName) {1452 if (!this.alreadyCreated.contains(beanName)) {1453 this.alreadyCreated.add(beanName);1454 }1455 }1456 1457 /** 1458 * Perform appropriate cleanup of cached metadata after bean creation failed.1459 *1460 *@parambeanName the name of the bean1461 */ 1462 protected voidcleanupAfterBeanCreationFailure(String beanName) {1463 this.alreadyCreated.remove(beanName);1464 }1465 1466 /** 1467 * Determine whether the specified bean is eligible for having1468 * its bean definition metadata cached.1469 *1470 *@parambeanName the name of the bean1471 *@return{@codetrue} if the bean's metadata may be cached1472 * at this point already1473 */ 1474 protected booleanisBeanEligibleForMetadataCaching(String beanName) {1475 return this.alreadyCreated.contains(beanName);1476 }1477 1478 /** 1479 * Remove the singleton instance (if any) for the given bean name,1480 * but only if it hasn't been used for other purposes than type checking.1481 *1482 *@parambeanName the name of the bean1483 *@return{@codetrue} if actually removed, {@codefalse} otherwise1484 */ 1485 protected booleanremoveSingletonIfCreatedForTypeCheckOnly(String beanName) {1486 if (!this.alreadyCreated.contains(beanName)) {1487 removeSingleton(beanName);1488 return true;1489 } else{1490 return false;1491 }1492 }1493 1494 /** 1495 * Get the object for the given bean instance, either the bean1496 * instance itself or its created object in case of a FactoryBean.1497 *1498 *@parambeanInstance the shared bean instance1499 *@paramname name that may include factory dereference prefix1500 *@parambeanName the canonical bean name1501 *@parammbd the merged bean definition1502 *@returnthe object to expose for the bean1503 */ 1504 protectedObject getObjectForBeanInstance(1505 Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {1506 1507 //Don't let calling code try to dereference the factory if the bean isn't a factory.1508 //& 开头.但是这个bean却又不是FactoryBean.说明有问题. &都应该是factorybean 1509 if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceofFactoryBean)) {1510 throw newBeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());1511 }1512 1513 //Now we have the bean instance, which may be a normal bean or a FactoryBean.1514 //If it's a FactoryBean, we use it to create a bean instance, unless the1515 //caller actually wants a reference to the factory.1516 //不是FactoryBean直接返回这个bean,&开头的话也直接返回这个bean. 1517 if (!(beanInstance instanceof FactoryBean) ||BeanFactoryUtils.isFactoryDereference(name)) {1518 returnbeanInstance;1519 }1520 1521 Object object = null;1522 if (mbd == null) {1523 //说明这个bean是需要从FactoryBean的getObject方法中返回的. 1524 object =getCachedObjectForFactoryBean(beanName);1525 }1526 if (object == null) { //没有cache.需要生成的情况1527 //Return bean instance from factory. 1528 FactoryBean<?> factory = (FactoryBean<?>) beanInstance;1529 //Caches object obtained from FactoryBean if it is a singleton. 1530 if (mbd == null &&containsBeanDefinition(beanName)) {1531 mbd = getMergedLocalBeanDefinition(beanName); //合并bean的定义 1532 }1533 boolean synthetic = (mbd != null &&mbd.isSynthetic());1534 object = getObjectFromFactoryBean(factory, beanName, !synthetic); //不是合成的bean的定义的话这个bean从工厂中生成需要调用postProcessObjectFromFactoryBean方法对bean进行加工,我觉得是因为父类中的这些后置处理bean当前工厂里没有 1535 }1536 returnobject;1537 }1538 1539 /** 1540 * Determine whether the given bean name is already in use within this factory,1541 * i.e. whether there is a local bean or alias registered under this name or1542 * an inner bean created with this name.1543 *1544 *@parambeanName the name to check1545 */ 1546 public booleanisBeanNameInUse(String beanName) {1547 return isAlias(beanName) || containsLocalBean(beanName) ||hasDependentBean(beanName);1548 }1549 1550 /** 1551 * Determine whether the given bean requires destruction on shutdown.1552 * <p>The default implementation checks the DisposableBean interface as well as1553 * a specified destroy method and registered DestructionAwareBeanPostProcessors.1554 *1555 *@parambean the bean instance to check1556 *@parammbd the corresponding bean definition1557 *@seeorg.springframework.beans.factory.DisposableBean1558 *@seeAbstractBeanDefinition#getDestroyMethodName()1559 *@seeorg.springframework.beans.factory.config.DestructionAwareBeanPostProcessor1560 */ 1561 protected booleanrequiresDestruction(Object bean, RootBeanDefinition mbd) {1562 return (bean != null && 1563 (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) ||hasDestructionAwareBeanPostProcessors()));1564 }1565 1566 /** 1567 * Add the given bean to the list of disposable beans in this factory,1568 * registering its DisposableBean interface and/or the given destroy method1569 * to be called on factory shutdown (if applicable). Only applies to singletons.1570 *1571 *@parambeanName the name of the bean1572 *@parambean the bean instance1573 *@parammbd the bean definition for the bean1574 *@seeRootBeanDefinition#isSingleton1575 *@seeRootBeanDefinition#getDependsOn1576 *@see#registerDisposableBean1577 *@see#registerDependentBean1578 */ 1579 protected voidregisterDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {1580 AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);1581 if (!mbd.isPrototype() &&requiresDestruction(bean, mbd)) {1582 if(mbd.isSingleton()) {1583 //Register a DisposableBean implementation that performs all destruction1584 //work for the given bean: DestructionAwareBeanPostProcessors,1585 //DisposableBean interface, custom destroy method. 1586 registerDisposableBean(beanName,1587 newDisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));1588 } else{1589 //A bean with a custom scope... 1590 Scope scope = this.scopes.get(mbd.getScope());1591 if (scope == null) {1592 throw new IllegalStateException("No Scope registered for scope '" + mbd.getScope() + "'");1593 }1594 scope.registerDestructionCallback(beanName,1595 newDisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));1596 }1597 }1598 }1599 1600 1601 //---------------------------------------------------------------------1602 //Abstract methods to be implemented by subclasses1603 //--------------------------------------------------------------------- 1604 1605 /** 1606 * Check if this bean factory contains a bean definition with the given name.1607 * Does not consider any hierarchy this factory may participate in.1608 * Invoked by {@codecontainsBean} when no cached singleton instance is found.1609 * <p>Depending on the nature of the concrete bean factory implementation,1610 * this operation might be expensive (for example, because of directory lookups1611 * in external registries). However, for listable bean factories, this usually1612 * just amounts to a local hash lookup: The operation is therefore part of the1613 * public interface there. The same implementation can serve for both this1614 * template method and the public interface method in that case.1615 * 当前这个BF不算父类的.是否包含了给定的beanname对应的Definition1616 *1617 *@parambeanName the name of the bean to look for1618 *@returnif this bean factory contains a bean definition with the given name1619 *@see#containsBean1620 *@seeorg.springframework.beans.factory.ListableBeanFactory#containsBeanDefinition1621 */ 1622 protected abstract booleancontainsBeanDefinition(String beanName);1623 1624 /** 1625 * Return the bean definition for the given bean name.1626 * Subclasses should normally implement caching, as this method is invoked1627 * by this class every time bean definition metadata is needed.1628 * <p>Depending on the nature of the concrete bean factory implementation,1629 * this operation might be expensive (for example, because of directory lookups1630 * in external registries). However, for listable bean factories, this usually1631 * just amounts to a local hash lookup: The operation is therefore part of the1632 * public interface there. The same implementation can serve for both this1633 * template method and the public interface method in that case.1634 * 根据beanname获取BeanDefinition,子类实现,可以用缓存1635 *1636 *@parambeanName the name of the bean to find a definition for1637 *@returnthe BeanDefinition for this prototype name (never {@codenull})1638 *@throwsorg.springframework.beans.factory.NoSuchBeanDefinitionException if the bean definition cannot be resolved1639 *@throwsBeansException in case of errors1640 *@seeRootBeanDefinition1641 *@seeChildBeanDefinition1642 *@seeorg.springframework.beans.factory.config.ConfigurableListableBeanFactory#getBeanDefinition1643 */ 1644 protected abstract BeanDefinition getBeanDefinition(String beanName) throwsBeansException;1645 1646 /** 1647 * Create a bean instance for the given merged bean definition (and arguments).1648 * The bean definition will already have been merged with the parent definition1649 * in case of a child definition.1650 * <p>All bean retrieval methods delegate to this method for actual bean creation.1651 *1652 *@parambeanName the name of the bean1653 *@parammbd the merged bean definition for the bean1654 *@paramargs explicit arguments to use for constructor or factory method invocation1655 *@returna new instance of the bean1656 *@throwsBeanCreationException if the bean could not be created1657 */ 1658 protected abstractObject createBean(String beanName, RootBeanDefinition mbd, Object[] args)1659 throwsBeanCreationException;1660 1661 }
View Code
一些方法加了注释,还有很多方法和其中的ifelse不明白为什么要这么写...
后续的一些逻辑要做实验才会明白了....
转载于:https://www.cnblogs.com/abcwt112/p/7574915.html
Spring 学习记录6 BeanFactory(2)相关推荐
- 我的Spring学习记录(二)
本篇就简单的说一下Bean的装配和AOP 本篇的项目是在上一篇我的Spring学习记录(一) 中项目的基础上进行开发的 1. 使用setter方法和构造方法装配Bean 1.1 前期准备 使用sett ...
- Spring学习记录(九)---通过工厂方法配置bean
1. 使用静态工厂方法创建Bean,用到一个工厂类 例子:一个Car类,有brand和price属性. 1 package com.guigu.spring.factory; 2 3 public c ...
- Spring 学习记录 冷兵器时代的故事
这篇文章的内容和 Spring 没什么关系,但还是分类到 Spring 学习了. 首先,我们来将一个故事. 很久很久以前,冷兵器时代,人们用弓和箭打仗. 版本1 public class BowAnd ...
- Spring学习记录
Spring相关 目录 文章目录 Spring相关 目录 前言 工厂设计模式 静态工厂模式 通用工厂模式 ApplicationContext ClassPathXmlApplicationConte ...
- spring学习记录(一)
一.spring概述 spring是什么 Spring是分层的 Java SE/EE应用 full-stack 轻量级开源框架,以 IoC(Inverse Of Control: 反转控制)和 AOP ...
- SSM之Spring学习记录
文章目录 IoC--把类告诉spring,让spring在你需要的时候创建相关类的对象 环境搭建 创建对象的三种方式 给Bean进行属性注入 DI(依赖注入) Spring 简化 mybatis AO ...
- Spring学习记录-Java 11运行eureka-server报javax.xml.bind.JAXBContext not present错
在pom.xml加入依赖就行 <dependency><groupId>org.glassfish.jaxb</groupId><artifactId> ...
- Spring学习总结一
Spring框架IoC与DI思想及应用 Spring学习总结一 1.Spring是什么 2.Spring的优点 2.1.关键概念 2.2.Spring的优点 3.Spring的架构图 3.1.核心容器 ...
- Spring——Spring学习教程(详细)(上篇)——IOC、AOP
本文是Spring的学习上篇,主要讲IOC和AOP. Spring的JDBCTemplete以及事务的知识,请见下篇. Spring--Spring学习教程(详细)(下篇)--JDBCTemplete ...
- springboot @cacheable不起作用_Springboot学习记录13 使用缓存:整合redis
本学习记录的代码,部分参考自gitee码云的如下工程.这个工程有详尽的Spingboot1.x教程.鸣谢! https://gitee.com/didispace/SpringBoot-Learnin ...
最新文章
- BZOJ 2257: [Jsoi2009]瓶子和燃料【数论:裴蜀定理】
- RSA加密的填充模式
- 深入理解javascript函数进阶系列第一篇——高阶函数
- [蓝桥杯][算法提高VIP]排列式-全排列
- git学习(6):删除github镜像
- 计算机重启恢复到推荐分辨率,为什么重启之后电脑界面分辨率会变
- Unity 使用BmFont制作艺术字体
- 距阵乘以一个未知距阵得单位矩阵 怎么算_干货分享:怎样假装一个带货流水过亿的直播达人?...
- 去掉Googl默认界面的logo下面的尴尬的文字,对面的菇凉请看过来!!!
- 日本房地产泡沫 Japan Real Estate Bubble
- 那些入行的Python工程师们还好吗?
- erdas遥感图像几何校正_实验二 ERDAS遥感图像的几何校正
- 超融合详细对比:市面各主流超融合产品及厂商优劣势解密
- c语言谢旻吕俊张军强答案,吕俊|
- strtol,strtoll,strtoul, strtoull字符串转化成数字
- 如何写一份详细的创业计划书?
- 【Java基础】Map遍历的5种方式
- 英国AI研究员揭开真相,中国人工智能为何能发展迅猛?
- 从头再来博客_免费课程:从头开始构建博客吗?
- 二叉树,满二叉树,完全二叉树 概念及其性质
热门文章
- SW-1、SW-2 通过 VSF 技术形成一台虚拟的逻辑设备
- YOLO算法之YOLOv2精讲
- YOLO学习笔记4——YOLOV2详解+论文解读
- 3dmax渲染计算机内存不足怎么办,解决3dmax渲染内存不够导致渲染失败的三种方法...
- 3DMAX全景漫游制作渲染教程,超详细的教程。
- cad高程测绘图lisp_CAD地形图高程信息快速提取的技术与实现
- 电视盒子刷鸿蒙系统,家里的智能电视能装鸿蒙系统吗?鸿蒙系统有哪些优势?...
- webgis期末考试试题_WebGIS考试参考试题
- 【软件测试】应用白盒测试实例
- 运行深度学习代码时报错RuntimeError: CUDA out of memory. Tried to allocate 482.00 MiB