/**
* Abstract base class for BeanFactory implementations,
* providing the full capabilities of the ConfigurableBeanFactory SPI.
* Does not assume a listable bean factory: can therefore(因此) also be used
* as base class for bean factory implementations which obtain bean definitions
* from some backend resource (where bean definition access is an expensive(昂貴的)) operation).
*
* This class provides a singleton cache (through its base class DefaultSingletonBeanRegistry,
* singleton/prototype determination(決定), FactoryBean handling, aliases,
* bean definition merging for child bean definitions,
* and bean destruction (DisposableBean interface, custom destroy methods). Furthermore, it can manage a bean factory
* hierarchy (delegating to the parent in case of an unknown bean), through implementing the HierarchicalBeanFactory interface
*
* The main template methods to be implemented by subclasses are #getBeanDefinition and #createBean,
* retrieving a bean definition for a given bean name and creating a bean instance for a given bean definition,respectively(各自地,獨自地).
* Default implementations of those operations can be found in DefaultListableBeanFactory and AbstractAutowireCapableBeanFactory.
*/publicabstractclassAbstractBeanFactoryextendsFactoryBeanRegistrySupportimplementsConfigurableBeanFactory{/** Parent bean factory, for bean inheritance support. */@Nullableprivate BeanFactory parentBeanFactory;// 父類容器/** ClassLoader to resolve bean class names with, if necessary. */@Nullableprivate ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();// 類加載器/** ClassLoader to temporarily resolve bean class names with, if necessary. */@Nullableprivate ClassLoader tempClassLoader;// 臨時類加載器/** Whether to cache bean metadata or rather eobtain(寧願重新獲取) it for every access. */// 是用 bean元數據緩存還是每次訪問時重新獲取privateboolean cacheBeanMetadata =true;// 是否開啓 bean元數據緩存/** Resolution strategy for expressions in bean definition values. */@Nullableprivate BeanExpressionResolver beanExpressionResolver;// bean表達式解析器/** Spring ConversionService to use instead of PropertyEditors. */@Nullableprivate ConversionService conversionService;// 類型轉換器/** Custom PropertyEditorRegistrars to apply to the beans of this factory. */privatefinal Set<PropertyEditorRegistrar> propertyEditorRegistrars =newLinkedHashSet<>(4);//屬性編輯器/** Custom PropertyEditors to apply to the beans of this factory. */privatefinal Map<Class<?>, Class<?extendsPropertyEditor>> customEditors =newHashMap<>(4);//類的屬性編輯器/** A custom TypeConverter to use, overriding the default PropertyEditor mechanism. */@Nullableprivate TypeConverter typeConverter;// 類性轉換器/** String resolvers to apply e.g. to annotation attribute values. */// 爲嵌入值(如註釋屬性)添加字符串解析privatefinal List<StringValueResolver> embeddedValueResolvers =newCopyOnWriteArrayList<>();/** BeanPostProcessors to apply in createBean. */// bean的後置處理 在bean的創建是應用privatefinal List<BeanPostProcessor> beanPostProcessors =newCopyOnWriteArrayList<>();/** Indicates whether any InstantiationAwareBeanPostProcessors have been registered. */// InstantiationAwareBeanPostProcessors 是否已註冊privatevolatileboolean hasInstantiationAwareBeanPostProcessors;/** Indicates whether any DestructionAwareBeanPostProcessors have been registered. */// DestructionAwareBeanPostProcessors 是否已經註冊privatevolatileboolean hasDestructionAwareBeanPostProcessors;/** Map from scope identifier(標識符,識別) String to corresponding(相應的,一致的) Scope. */// 作用域privatefinal Map<String, Scope> scopes =newLinkedHashMap<>(8);/** Security context used when running with a SecurityManager. */@Nullable// 提供安全作用 權限控制private SecurityContextProvider securityContextProvider;/** Map from bean name to merged RootBeanDefinition. 合併後的BeanDefinition*/privatefinal Map<String, RootBeanDefinition> mergedBeanDefinitions =newConcurrentHashMap<>(256);/** Names of beans that have already been created at least once. */// bean的實例是否已經創建privatefinal Set<String> alreadyCreated = Collections.newSetFromMap(newConcurrentHashMap<>(256));/** Names of beans that are currently in creation. */// 本地緩存,正在創建的原型bean。這邊用本地線程,是因爲其他線程創建bean與當前線程不衝突privatefinal ThreadLocal<Object> prototypesCurrentlyInCreation =newNamedThreadLocal<>("Prototype beans currently in creation");/**
* Create a new AbstractBeanFactory.
*/publicAbstractBeanFactory(){}/**
* Create a new AbstractBeanFactory with the given parent.
*/publicAbstractBeanFactory(@Nullable BeanFactory parentBeanFactory){this.parentBeanFactory = parentBeanFactory;}//---------------------------------------------------------------------// Implementation of BeanFactory interface //---------------------------------------------------------------------@Overridepublic Object getBean(String name)throws BeansException {returndoGetBean(name, null, null,false);}@Overridepublic<T> T getBean(String name, Class<T> requiredType)throws BeansException {returndoGetBean(name, requiredType, null,false);}@Overridepublic Object getBean(String name, Object... args)throws BeansException {returndoGetBean(name, null, args,false);}public<T> T getBean(String name,@Nullable Class<T> requiredType,@Nullable Object... args)throws BeansException {returndoGetBean(name, requiredType, args,false);}/**
* Return an instance, which may be shared or independent, of the specified bean.
* 返回一個指定的bean實例,可能是 共享的或者獨立的bean-->單例或原型 bean
* @param name bean的名稱
* @param requiredType 返回的類型
* @param args 傳遞的構造參數
* @param typeCheckOnly 檢查類型
* @return 返回bean實例
* @throws BeansException if the bean could not be created
*/@SuppressWarnings("unchecked")protected<T> T doGetBean(final String name,@Nullablefinal Class<T> requiredType,@Nullablefinal Object[] args,boolean typeCheckOnly)throws BeansException {//獲取beanName,這邊有三種形式,一個是原始的beanName,一個是加了&的,一個是別名 final String beanName =transformedBeanName(name);
Object bean;// Eagerly(急切地,渴望) check singleton cache for manually registered singletons.// 是否已經創建了
Object sharedInstance =getSingleton(beanName);//已經創建了,且沒有構造參數,進入這個方法,如果有構造參數,往else走,// 也就是說不從獲取bean,而直接創建beanif(sharedInstance != null && args == null){if(logger.isTraceEnabled()){if(isSingletonCurrentlyInCreation(beanName)){
logger.trace("Returning eagerly cached instance of singleton bean '"+ beanName +"' that is not fully initialized yet - a consequence of a circular reference");}else{
logger.trace("Returning cached instance of singleton bean '"+ beanName +"'");}}// 如果是普通bean,直接返回,是FactoryBean,返回他的getObject
bean =getObjectForBeanInstance(sharedInstance, name, beanName, null);}else{// Fail if we're already creating this bean instance:// We're assumably within a circular reference.// 沒創建過bean或者是原型bean的情況或者有參數的情況// 創建過Prototype的bean,會循環引用,拋出異常,單例才嘗試解決循環依賴的問題if(isPrototypeCurrentlyInCreation(beanName)){thrownewBeanCurrentlyInCreationException(beanName);}// Check if bean definition exists in this factory.// 父容器存在,本地沒有當前beanName,從父容器獲取
BeanFactory parentBeanFactory =getParentBeanFactory();if(parentBeanFactory != null &&!containsBeanDefinition(beanName)){// Not found -> check parent.// 處理後,如果是加&,就補上&
String nameToLookup =originalBeanName(name);if(parentBeanFactory instanceofAbstractBeanFactory){return((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);}elseif(args != null){// Delegation to parent with explicit args.return(T) parentBeanFactory.getBean(nameToLookup, args);}elseif(requiredType != null){// No args -> delegate to standard getBean method.return parentBeanFactory.getBean(nameToLookup, requiredType);}else{return(T) parentBeanFactory.getBean(nameToLookup);}}if(!typeCheckOnly){// typeCheckOnly爲false,將beanName放入alreadyCreated中,並清除bean合併定義markBeanAsCreated(beanName);}try{// 獲取bean的合併定義final RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);// 抽象類檢查checkMergedBeanDefinition(mbd, beanName, args);// Guarantee(保證) initialization of beans that the current bean depends on.// 如果有依賴的情況,先初始化依賴的bean
String[] dependsOn = mbd.getDependsOn();// 獲取所有的依賴bean名稱if(dependsOn != null){for(String dep : dependsOn){// 檢查是否循環依賴,a依賴b,b依賴a。包括傳遞的依賴,比如a依賴b,b依賴c,c依賴aif(isDependent(beanName, dep)){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"Circular depends-on relationship between '"+ beanName +"' and '"+ dep +"'");}// 註冊依賴關係registerDependentBean(dep, beanName);try{// 初始化依賴的beangetBean(dep);}catch(NoSuchBeanDefinitionException ex){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"'"+ beanName +"' depends on missing bean '"+ dep +"'", ex);}}}// Create bean instance.if(mbd.isSingleton()){// 如果是單例
sharedInstance =getSingleton(beanName,()->{try{returncreateBean(beanName, mbd, args);// 創建bean}catch(BeansException ex){// Explicitly remove instance from singleton cache: It might have been put there// eagerly by the creation process, to allow for circular reference resolution.// Also remove any beans that received a temporary reference to the bean.destroySingleton(beanName);throw ex;}});// 如果是普通bean,直接返回,是FactoryBean,返回他的getObject
bean =getObjectForBeanInstance(sharedInstance, name, beanName, mbd);}elseif(mbd.isPrototype()){// 原型bean的創建// It's a prototype -> create a new instance.
Object prototypeInstance = null;try{// 加入prototypesCurrentlyInCreation,說明正在創建beforePrototypeCreation(beanName);// 創建bean
prototypeInstance =createBean(beanName, mbd, args);}finally{// 移除prototypesCurrentlyInCreation,說明已經創建結束afterPrototypeCreation(beanName);}// 如果是普通bean,直接返回,是FactoryBean,返回他的getObject
bean =getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);}else{// scope bean創建
String scopeName = mbd.getScope();final Scope scope =this.scopes.get(scopeName);if(scope == null){thrownewIllegalStateException("No Scope registered for scope name '"+ scopeName +"'");}try{
Object scopedInstance = scope.get(beanName,()->{beforePrototypeCreation(beanName);try{returncreateBean(beanName, mbd, args);}finally{afterPrototypeCreation(beanName);}});
bean =getObjectForBeanInstance(scopedInstance, name, beanName, mbd);}catch(IllegalStateException ex){thrownewBeanCreationException(beanName,"Scope '"+ scopeName +"' is not active for the current thread; consider "+"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);}}}catch(BeansException ex){cleanupAfterBeanCreationFailure(beanName);throw ex;}}// Check if required type matches the type of the actual bean instance.// 檢查創建的的bean是需要的類型 類型檢查,轉換if(requiredType != null &&!requiredType.isInstance(bean)){try{
T convertedBean =getTypeConverter().convertIfNecessary(bean, requiredType);if(convertedBean == null){thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}return convertedBean;}catch(TypeMismatchException ex){if(logger.isTraceEnabled()){
logger.trace("Failed to convert bean '"+ name +"' to required type '"+
ClassUtils.getQualifiedName(requiredType)+"'", ex);}thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}}return(T) bean;}@Override// 是否已經創建bean或者定義好了bean,包括當前容器以及父容器publicbooleancontainsBean(String name){
String beanName =transformedBeanName(name);// 已創建單例bean或者包括bean的定義if(containsSingleton(beanName)||containsBeanDefinition(beanName)){// 如果不是&開頭的,直接返回// 如果是&開頭的,判斷是否是FactoryBean,沒有找到從父類找return(!BeanFactoryUtils.isFactoryDereference(name)||isFactoryBean(name));}// Not found -> check parent. // 當前容器沒找到,去父類找
BeanFactory parentBeanFactory =getParentBeanFactory();return(parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name)));}@Override// 指定beanName是否是單例,包括普通的bean和FactoryBean,包括當前容器以及父容器publicbooleanisSingleton(String name)throws NoSuchBeanDefinitionException {
String beanName =transformedBeanName(name);// 如果已經實例化了
Object beanInstance =getSingleton(beanName,false);if(beanInstance != null){if(beanInstance instanceofFactoryBean){// 是FactoryBean類型,name要&開頭或者FactoryBean中isSingleton方法返回爲truereturn(BeanFactoryUtils.isFactoryDereference(name)||((FactoryBean<?>) beanInstance).isSingleton());}else{// 如果不是FactoryBean,name就不能是&開頭return!BeanFactoryUtils.isFactoryDereference(name);}}// No singleton instance found -> check bean definition.// 如果當前容器還沒實例化,去父類找
BeanFactory parentBeanFactory =getParentBeanFactory();if(parentBeanFactory != null &&!containsBeanDefinition(beanName)){// No bean definition found in this factory -> delegate to parent.return parentBeanFactory.isSingleton(originalBeanName(name));}// 父類也沒有,根據定義來判斷是否是單例// 獲取合併後的BeanDefinition
RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);// In case of FactoryBean, return singleton status of created object if not a dereference.if(mbd.isSingleton()){// 如果定義了是單例,判斷是否是FactoryBean,如果是FactoryBean,name就要是&開頭if(isFactoryBean(beanName, mbd)){if(BeanFactoryUtils.isFactoryDereference(name)){returntrue;}// 如果是單例,但是name不是&開頭,就重新獲取factoryBean,再判斷是否是單例
FactoryBean<?> factoryBean =(FactoryBean<?>)getBean(FACTORY_BEAN_PREFIX + beanName);return factoryBean.isSingleton();}else{// 如果不是FactoryBean,就不能是&開頭return!BeanFactoryUtils.isFactoryDereference(name);}}else{returnfalse;}}@Override// 指定beanName是否是原型,包括普通的bean和FactoryBean,包括當前容器以及父容器publicbooleanisPrototype(String name)throws NoSuchBeanDefinitionException {
String beanName =transformedBeanName(name);// 有父容器,且沒有beanName的定義,從父容器中查找
BeanFactory parentBeanFactory =getParentBeanFactory();if(parentBeanFactory != null &&!containsBeanDefinition(beanName)){// No bean definition found in this factory -> delegate to parent.return parentBeanFactory.isPrototype(originalBeanName(name));}// 沒有再從當前容器查找
RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);if(mbd.isPrototype()){// In case of FactoryBean, return singleton status of created object if not a dereference.// 如果是普通的bean返回true,如果是&開頭的,且是FactoryBean,返回truereturn(!BeanFactoryUtils.isFactoryDereference(name)||isFactoryBean(beanName, mbd));}// Singleton or scoped - not a prototype.// However, FactoryBean may still produce a prototype object...// 如果不是Prototype,且是&開頭,&開頭就是FactoryBean,FactoryBean是單例的,所以是返回falseif(BeanFactoryUtils.isFactoryDereference(name)){returnfalse;}// 如果是FactoryBean,判斷是否有Singleton或者Prototypeif(isFactoryBean(beanName, mbd)){final FactoryBean<?> fb =(FactoryBean<?>)getBean(FACTORY_BEAN_PREFIX + beanName);if(System.getSecurityManager()!= null){return AccessController.doPrivileged((PrivilegedAction<Boolean>)()->((fb instanceofSmartFactoryBean&&((SmartFactoryBean<?>) fb).isPrototype())||!fb.isSingleton()),getAccessControlContext());}else{return((fb instanceofSmartFactoryBean&&((SmartFactoryBean<?>) fb).isPrototype())||!fb.isSingleton());}}else{returnfalse;}}@Override// 指定的beanName是否與類型匹配publicbooleanisTypeMatch(String name, ResolvableType typeToMatch)throws NoSuchBeanDefinitionException {returnisTypeMatch(name, typeToMatch,true);}/**
* Internal extended variant of isTypeMatch(String, ResolvableType)
* to check whether the bean with the given name matches the specified type. Allow
* additional constraints to be applied to ensure that beans are not created early.
*/// 指定的beanName是否與類型匹配protectedbooleanisTypeMatch(String name, ResolvableType typeToMatch,boolean allowFactoryBeanInit)throws NoSuchBeanDefinitionException {
String beanName =transformedBeanName(name);boolean isFactoryDereference = BeanFactoryUtils.isFactoryDereference(name);// Check manually registered singletons.// 獲取單例
Object beanInstance =getSingleton(beanName,false);// 不爲空並且不是NullBean類型if(beanInstance != null && beanInstance.getClass()!= NullBean.class){if(beanInstance instanceofFactoryBean){if(!isFactoryDereference){// 不是&開頭,獲取FactoryBean的getObjectType類型,再來比較
Class<?> type =getTypeForFactoryBean((FactoryBean<?>) beanInstance);return(type != null && typeToMatch.isAssignableFrom(type));}else{// name是&開頭,直接判斷類型FactoryBean return typeToMatch.isInstance(beanInstance);}}elseif(!isFactoryDereference){// 普通bean,且沒有&開頭if(typeToMatch.isInstance(beanInstance)){// Direct match for exposed instance?returntrue;}// 泛型且有beanName的定義elseif(typeToMatch.hasGenerics()&&containsBeanDefinition(beanName)){// Generics potentially only match on the target class, not on the proxy...// 合併定義
RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);
Class<?> targetType = mbd.getTargetType();if(targetType != null && targetType != ClassUtils.getUserClass(beanInstance)){// Check raw class match as well, making sure it's exposed on the proxy.
Class<?> classToMatch = typeToMatch.resolve();if(classToMatch != null &&!classToMatch.isInstance(beanInstance)){returnfalse;}if(typeToMatch.isAssignableFrom(targetType)){returntrue;}}
ResolvableType resolvableType = mbd.targetType;if(resolvableType == null){
resolvableType = mbd.factoryMethodReturnType;}return(resolvableType != null && typeToMatch.isAssignableFrom(resolvableType));}}returnfalse;}// 已經創建了,但是沒有bean的定義,說明是空的註冊進來elseif(containsSingleton(beanName)&&!containsBeanDefinition(beanName)){// null instance registeredreturnfalse;}// No singleton instance found -> check bean definition.// 從父類找
BeanFactory parentBeanFactory =getParentBeanFactory();if(parentBeanFactory != null &&!containsBeanDefinition(beanName)){// No bean definition found in this factory -> delegate to parent.return parentBeanFactory.isTypeMatch(originalBeanName(name), typeToMatch);}// Retrieve corresponding bean definition.// 重新檢索相應的bean定義
RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();// Setup the types that we want to match against
Class<?> classToMatch = typeToMatch.resolve();if(classToMatch == null){
classToMatch = FactoryBean.class;}
Class<?>[] typesToMatch =(FactoryBean.class== classToMatch ?newClass<?>[]{classToMatch}:newClass<?>[]{FactoryBean.class, classToMatch});// Attempt to predict the bean type
Class<?> predictedType = null;// We're looking for a regular reference but we're a factory bean that has// a decorated bean definition. The target bean should be the same type// as FactoryBean would ultimately return.if(!isFactoryDereference && dbd != null &&isFactoryBean(beanName, mbd)){// We should only attempt if the user explicitly set lazy-init to true// and we know the merged bean definition is for a factory bean.if(!mbd.isLazyInit()|| allowFactoryBeanInit){
RootBeanDefinition tbd =getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
Class<?> targetType =predictBeanType(dbd.getBeanName(), tbd, typesToMatch);if(targetType != null &&!FactoryBean.class.isAssignableFrom(targetType)){
predictedType = targetType;}}}// If we couldn't use the target type, try regular prediction.if(predictedType == null){
predictedType =predictBeanType(beanName, mbd, typesToMatch);if(predictedType == null){returnfalse;}}// Attempt to get the actual ResolvableType for the bean.
ResolvableType beanType = null;// If it's a FactoryBean, we want to look at what it creates, not the factory class.if(FactoryBean.class.isAssignableFrom(predictedType)){if(beanInstance == null &&!isFactoryDereference){
beanType =getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit);
predictedType = beanType.resolve();if(predictedType == null){returnfalse;}}}elseif(isFactoryDereference){// Special case: A SmartInstantiationAwareBeanPostProcessor returned a non-FactoryBean// type but we nevertheless are being asked to dereference a FactoryBean...// Let's check the original bean class and proceed with it if it is a FactoryBean.
predictedType =predictBeanType(beanName, mbd, FactoryBean.class);if(predictedType == null ||!FactoryBean.class.isAssignableFrom(predictedType)){returnfalse;}}// We don't have an exact type but if bean definition target type or the factory// method return type matches the predicted type then we can use that.if(beanType == null){
ResolvableType definedType = mbd.targetType;if(definedType == null){
definedType = mbd.factoryMethodReturnType;}if(definedType != null && definedType.resolve()== predictedType){
beanType = definedType;}}// If we have a bean type use it so that generics are consideredif(beanType != null){return typeToMatch.isAssignableFrom(beanType);}// If we don't have a bean type, fallback to the predicted typereturn typeToMatch.isAssignableFrom(predictedType);}@OverridepublicbooleanisTypeMatch(String name, Class<?> typeToMatch)throws NoSuchBeanDefinitionException {returnisTypeMatch(name, ResolvableType.forRawClass(typeToMatch));}@Override@Nullable// 獲取指定beanName的類型public Class<?>getType(String name)throws NoSuchBeanDefinitionException {returngetType(name,true);}@Override@Nullablepublic Class<?>getType(String name,boolean allowFactoryBeanInit)throws NoSuchBeanDefinitionException {
String beanName =transformedBeanName(name);// Check manually registered singletons.// 檢查手動註冊的單例
Object beanInstance =getSingleton(beanName,false);// 已經實例化並且不是NullBeanif(beanInstance != null && beanInstance.getClass()!= NullBean.class){// 如果是FactoryBean,且沒有&,說明是取FactoryBean的getObjectType類型if(beanInstance instanceofFactoryBean&&!BeanFactoryUtils.isFactoryDereference(name)){returngetTypeForFactoryBean((FactoryBean<?>) beanInstance);}else{// 直接返回類型return beanInstance.getClass();}}// No singleton instance found -> check bean definition.// 從父容器中獲取bean的類型
BeanFactory parentBeanFactory =getParentBeanFactory();if(parentBeanFactory != null &&!containsBeanDefinition(beanName)){// No bean definition found in this factory -> delegate to parent.return parentBeanFactory.getType(originalBeanName(name));}// 獲取bean合併的定義
RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);// Check decorated(裝飾) bean definition, if any: We assume it'll be easier// to determine the decorated bean's type than the proxy's type.// 獲取 BeanDefinitionHolder 裝飾器
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();if(dbd != null &&!BeanFactoryUtils.isFactoryDereference(name)){
RootBeanDefinition tbd =getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
Class<?> targetClass =predictBeanType(dbd.getBeanName(), tbd);if(targetClass != null &&!FactoryBean.class.isAssignableFrom(targetClass)){return targetClass;}}
Class<?> beanClass =predictBeanType(beanName, mbd);// Check bean class whether we're dealing with a FactoryBean.if(beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)){if(!BeanFactoryUtils.isFactoryDereference(name)){// If it's a FactoryBean, we want to look at what it creates, not at the factory class.returngetTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit).resolve();}else{return beanClass;}}else{return(!BeanFactoryUtils.isFactoryDereference(name)? beanClass : null);}}@Override// 獲取bean的別名public String[]getAliases(String name){
String beanName =transformedBeanName(name);
List<String> aliases =newArrayList<>();boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX);
String fullBeanName = beanName;if(factoryPrefix){
fullBeanName = FACTORY_BEAN_PREFIX + beanName;}if(!fullBeanName.equals(name)){
aliases.add(fullBeanName);}
String[] retrievedAliases =super.getAliases(beanName);
String prefix = factoryPrefix ? FACTORY_BEAN_PREFIX :"";for(String retrievedAlias : retrievedAliases){
String alias = prefix + retrievedAlias;if(!alias.equals(name)){
aliases.add(alias);}}// 沒實例化過且沒有bean的定義,從父類查找if(!containsSingleton(beanName)&&!containsBeanDefinition(beanName)){
BeanFactory parentBeanFactory =getParentBeanFactory();if(parentBeanFactory != null){
aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName)));}}return StringUtils.toStringArray(aliases);}//---------------------------------------------------------------------// Implementation of HierarchicalBeanFactory interface//---------------------------------------------------------------------@Override@Nullablepublic BeanFactory getParentBeanFactory(){returnthis.parentBeanFactory;}@Override// 當前容器是否有指定的beanpublicbooleancontainsLocalBean(String name){
String beanName =transformedBeanName(name);return((containsSingleton(beanName)||containsBeanDefinition(beanName))&&(!BeanFactoryUtils.isFactoryDereference(name)||isFactoryBean(beanName)));}//---------------------------------------------------------------------// Implementation of ConfigurableBeanFactory interface//---------------------------------------------------------------------@OverridepublicvoidsetParentBeanFactory(@Nullable BeanFactory parentBeanFactory){if(this.parentBeanFactory != null &&this.parentBeanFactory != parentBeanFactory){thrownewIllegalStateException("Already associated with parent BeanFactory: "+this.parentBeanFactory);}this.parentBeanFactory = parentBeanFactory;}@OverridepublicvoidsetBeanClassLoader(@Nullable ClassLoader beanClassLoader){this.beanClassLoader =(beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader());}@Override@Nullablepublic ClassLoader getBeanClassLoader(){returnthis.beanClassLoader;}@Override// 設置臨時加載器,如果涉及到加載時編織,通常只指定一個臨時類裝入器,以確保實際的bean類被儘可能延遲地裝入publicvoidsetTempClassLoader(@Nullable ClassLoader tempClassLoader){this.tempClassLoader = tempClassLoader;}@Override@Nullablepublic ClassLoader getTempClassLoader(){returnthis.tempClassLoader;}@Override// bean的元數據緩存,默認爲true。如果爲false,每次創建bean都要從類加載器獲取信息publicvoidsetCacheBeanMetadata(boolean cacheBeanMetadata){this.cacheBeanMetadata = cacheBeanMetadata;}@OverridepublicbooleanisCacheBeanMetadata(){returnthis.cacheBeanMetadata;}@OverridepublicvoidsetBeanExpressionResolver(@Nullable BeanExpressionResolver resolver){this.beanExpressionResolver = resolver;}@Override@Nullablepublic BeanExpressionResolver getBeanExpressionResolver(){returnthis.beanExpressionResolver;}@OverridepublicvoidsetConversionService(@Nullable ConversionService conversionService){this.conversionService = conversionService;}@Override@Nullablepublic ConversionService getConversionService(){returnthis.conversionService;}@OverridepublicvoidaddPropertyEditorRegistrar(PropertyEditorRegistrar registrar){
Assert.notNull(registrar,"PropertyEditorRegistrar must not be null");this.propertyEditorRegistrars.add(registrar);}/**
* Return the set of PropertyEditorRegistrars.
*/public Set<PropertyEditorRegistrar>getPropertyEditorRegistrars(){returnthis.propertyEditorRegistrars;}@OverridepublicvoidregisterCustomEditor(Class<?> requiredType, Class<?extendsPropertyEditor> propertyEditorClass){
Assert.notNull(requiredType,"Required type must not be null");
Assert.notNull(propertyEditorClass,"PropertyEditor class must not be null");this.customEditors.put(requiredType, propertyEditorClass);}@OverridepublicvoidcopyRegisteredEditorsTo(PropertyEditorRegistry registry){registerCustomEditors(registry);}/**
* Return the map of custom editors, with Classes as keys and PropertyEditor classes as values.
*/public Map<Class<?>, Class<?extendsPropertyEditor>>getCustomEditors(){returnthis.customEditors;}@OverridepublicvoidsetTypeConverter(TypeConverter typeConverter){this.typeConverter = typeConverter;}/**
* Return the custom TypeConverter to use, if any.
* @return the custom TypeConverter, or {@code null} if none specified
*/@Nullableprotected TypeConverter getCustomTypeConverter(){returnthis.typeConverter;}@Overridepublic TypeConverter getTypeConverter(){
TypeConverter customConverter =getCustomTypeConverter();if(customConverter != null){return customConverter;}else{// Build default TypeConverter, registering custom editors.// 沒有設值就初始化一個SimpleTypeConverter
SimpleTypeConverter typeConverter =newSimpleTypeConverter();
typeConverter.setConversionService(getConversionService());registerCustomEditors(typeConverter);return typeConverter;}}@OverridepublicvoidaddEmbeddedValueResolver(StringValueResolver valueResolver){
Assert.notNull(valueResolver,"StringValueResolver must not be null");this.embeddedValueResolvers.add(valueResolver);}@OverridepublicbooleanhasEmbeddedValueResolver(){return!this.embeddedValueResolvers.isEmpty();}@Override@Nullable// 解析給定的嵌入值public String resolveEmbeddedValue(@Nullable String value){if(value == null){return null;}
String result = value;for(StringValueResolver resolver :this.embeddedValueResolvers){
result = resolver.resolveStringValue(result);if(result == null){return null;}}return result;}@Override// 增加後置處理器publicvoidaddBeanPostProcessor(BeanPostProcessor beanPostProcessor){
Assert.notNull(beanPostProcessor,"BeanPostProcessor must not be null");// Remove from old position, if any // 移除舊的,保證順序this.beanPostProcessors.remove(beanPostProcessor);// Track whether it is instantiation/destruction aware// 如果是 instantiation/destruction aware 標誌爲置trueif(beanPostProcessor instanceofInstantiationAwareBeanPostProcessor){this.hasInstantiationAwareBeanPostProcessors =true;}if(beanPostProcessor instanceofDestructionAwareBeanPostProcessor){this.hasDestructionAwareBeanPostProcessors =true;}// Add to end of listthis.beanPostProcessors.add(beanPostProcessor);}@Override// 獲取後置出處理器的個數publicintgetBeanPostProcessorCount(){returnthis.beanPostProcessors.size();}/**
* Return the list of BeanPostProcessors that will get applied
* to beans created with this factory.
*/public List<BeanPostProcessor>getBeanPostProcessors(){returnthis.beanPostProcessors;}/**
* Return whether this factory holds a InstantiationAwareBeanPostProcessor
* that will get applied to singleton beans on shutdown.
*/protectedbooleanhasInstantiationAwareBeanPostProcessors(){returnthis.hasInstantiationAwareBeanPostProcessors;}/**
* Return whether this factory holds a DestructionAwareBeanPostProcessor
* that will get applied to singleton beans on shutdown.
*/protectedbooleanhasDestructionAwareBeanPostProcessors(){returnthis.hasDestructionAwareBeanPostProcessors;}@Override// 註冊作用域publicvoidregisterScope(String scopeName, Scope scope){
Assert.notNull(scopeName,"Scope identifier must not be null");
Assert.notNull(scope,"Scope must not be null");// 單例和原型 不允許再註冊if(SCOPE_SINGLETON.equals(scopeName)|| SCOPE_PROTOTYPE.equals(scopeName)){thrownewIllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'");}
Scope previous =this.scopes.put(scopeName, scope);if(previous != null && previous != scope){if(logger.isDebugEnabled()){
logger.debug("Replacing scope '"+ scopeName +"' from ["+ previous +"] to ["+ scope +"]");}}else{if(logger.isTraceEnabled()){
logger.trace("Registering scope '"+ scopeName +"' with implementation ["+ scope +"]");}}}@Override// 獲取作用域 名稱public String[]getRegisteredScopeNames(){return StringUtils.toStringArray(this.scopes.keySet());}@Override@Nullable// 通過名稱獲取作用域 public Scope getRegisteredScope(String scopeName){
Assert.notNull(scopeName,"Scope identifier must not be null");returnthis.scopes.get(scopeName);}/**
* Set the security context provider for this bean factory. If a security manager
* is set, interaction with the user code will be executed using the privileged
* of the provided security context.
*/publicvoidsetSecurityContextProvider(SecurityContextProvider securityProvider){this.securityContextProvider = securityProvider;}/**
* Delegate the creation of the access control context to the
* {@link #setSecurityContextProvider SecurityContextProvider}.
*/@Overridepublic AccessControlContext getAccessControlContext(){return(this.securityContextProvider != null ?this.securityContextProvider.getAccessControlContext():
AccessController.getContext());}@OverridepublicvoidcopyConfigurationFrom(ConfigurableBeanFactory otherFactory){
Assert.notNull(otherFactory,"BeanFactory must not be null");setBeanClassLoader(otherFactory.getBeanClassLoader());setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());setConversionService(otherFactory.getConversionService());if(otherFactory instanceofAbstractBeanFactory){
AbstractBeanFactory otherAbstractFactory =(AbstractBeanFactory) otherFactory;this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars);this.customEditors.putAll(otherAbstractFactory.customEditors);this.typeConverter = otherAbstractFactory.typeConverter;this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors);this.hasInstantiationAwareBeanPostProcessors =this.hasInstantiationAwareBeanPostProcessors ||
otherAbstractFactory.hasInstantiationAwareBeanPostProcessors;this.hasDestructionAwareBeanPostProcessors =this.hasDestructionAwareBeanPostProcessors ||
otherAbstractFactory.hasDestructionAwareBeanPostProcessors;this.scopes.putAll(otherAbstractFactory.scopes);this.securityContextProvider = otherAbstractFactory.securityContextProvider;}else{setTypeConverter(otherFactory.getTypeConverter());
String[] otherScopeNames = otherFactory.getRegisteredScopeNames();for(String scopeName : otherScopeNames){this.scopes.put(scopeName, otherFactory.getRegisteredScope(scopeName));}}}/**
* Return a 'merged' BeanDefinition for the given bean name,
* merging a child bean definition with its parent if necessary.
* This getMergedBeanDefinition considers bean definition
* in ancestors as well. 合併bean的定義,包括父類繼承下來的
*/@Overridepublic BeanDefinition getMergedBeanDefinition(String name)throws BeansException {
String beanName =transformedBeanName(name);// Efficiently check whether bean definition exists in this factory.// 如果當前容器沒有,且父類是ConfigurableBeanFactory類型,去父類找if(!containsBeanDefinition(beanName)&&getParentBeanFactory()instanceofConfigurableBeanFactory){return((ConfigurableBeanFactory)getParentBeanFactory()).getMergedBeanDefinition(beanName);}// Resolve merged bean definition locally. 去本地找returngetMergedLocalBeanDefinition(beanName);}@Override// 是否是FactoryBean類型publicbooleanisFactoryBean(String name)throws NoSuchBeanDefinitionException {// 獲取beanName
String beanName =transformedBeanName(name);// 後去bean實例
Object beanInstance =getSingleton(beanName,false);// 已經實例化直接判斷if(beanInstance != null){return(beanInstance instanceofFactoryBean);}// No singleton instance found -> check bean definition.// 沒有實例化,從父類判斷if(!containsBeanDefinition(beanName)&&getParentBeanFactory()instanceofConfigurableBeanFactory){// No bean definition found in this factory -> delegate to parent.return((ConfigurableBeanFactory)getParentBeanFactory()).isFactoryBean(name);}returnisFactoryBean(beanName,getMergedLocalBeanDefinition(beanName));}@Override// 是否正在創建的bean, 包括單例和原型publicbooleanisActuallyInCreation(String beanName){return(isSingletonCurrentlyInCreation(beanName)||isPrototypeCurrentlyInCreation(beanName));}/**
* Return whether the specified prototype bean is currently in creation
* (within the current thread). 是否原型bean正在創建中
*/protectedbooleanisPrototypeCurrentlyInCreation(String beanName){
Object curVal =this.prototypesCurrentlyInCreation.get();// 當前線程有值,說明有在創建原型// 如果相等,或者在set中,說明創建的多例有包括指定的beanreturn(curVal != null &&(curVal.equals(beanName)||(curVal instanceofSet&&((Set<?>) curVal).contains(beanName))));}/**
* Callback before prototype creation.
* The default implementation register the prototype as currently in creation.
* 原型創建前,把beanName加入到prototypesCurrentlyInCreation,如果是string,說明已加入一個,轉換爲set
*/@SuppressWarnings("unchecked")protectedvoidbeforePrototypeCreation(String beanName){
Object curVal =this.prototypesCurrentlyInCreation.get();if(curVal == null){this.prototypesCurrentlyInCreation.set(beanName);}elseif(curVal instanceofString){
Set<String> beanNameSet =newHashSet<>(2);
beanNameSet.add((String) curVal);
beanNameSet.add(beanName);this.prototypesCurrentlyInCreation.set(beanNameSet);}else{
Set<String> beanNameSet =(Set<String>) curVal;
beanNameSet.add(beanName);}}/**
* Callback after prototype creation.
* The default implementation marks the prototype as not in creation anymore.
* 原型創建完了,從prototypesCurrentlyInCreation移除
*/@SuppressWarnings("unchecked")protectedvoidafterPrototypeCreation(String beanName){
Object curVal =this.prototypesCurrentlyInCreation.get();if(curVal instanceofString){this.prototypesCurrentlyInCreation.remove();}elseif(curVal instanceofSet){
Set<String> beanNameSet =(Set<String>) curVal;
beanNameSet.remove(beanName);if(beanNameSet.isEmpty()){this.prototypesCurrentlyInCreation.remove();}}}@Override// 銷燬beanpublicvoiddestroyBean(String beanName, Object beanInstance){destroyBean(beanName, beanInstance,getMergedLocalBeanDefinition(beanName));}/**
* Destroy the given bean instance (usually a prototype instance
* obtained from this factory) according to the given bean definition.
*/protectedvoiddestroyBean(String beanName, Object bean, RootBeanDefinition mbd){newDisposableBeanAdapter(bean, beanName, mbd,getBeanPostProcessors(),getAccessControlContext()).destroy();}@Override// scope的bean 銷燬publicvoiddestroyScopedBean(String beanName){
RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);if(mbd.isSingleton()|| mbd.isPrototype()){// 單例和原型不能銷燬 thrownewIllegalArgumentException("Bean name '"+ beanName +"' does not correspond to an object in a mutable scope");}
String scopeName = mbd.getScope();// 沒有對應的scope,不能刪除
Scope scope =this.scopes.get(scopeName);if(scope == null){thrownewIllegalStateException("No Scope SPI registered for scope name '"+ scopeName +"'");}
Object bean = scope.remove(beanName);if(bean != null){destroyBean(beanName, bean, mbd);}}//---------------------------------------------------------------------// Implementation methods//---------------------------------------------------------------------/**
* Return the bean name, stripping out the factory dereference prefix if necessary,
* and resolving aliases to canonical names.
* 獲取beanName,有可能傳過來的是原始的beanName,有可能是加了&的,有可能是別名。
* 如果是加了&的,先去除,再獲取。如果是別名,先遞歸到最原始的別名,再獲取beanName
*/protected String transformedBeanName(String name){returncanonicalName(BeanFactoryUtils.transformedBeanName(name));}/**
* Determine the original bean name, resolving locally defined aliases to canonical names.
* 獲取原始的beanName,如果有&,要加上&
*/protected String originalBeanName(String name){
String beanName =transformedBeanName(name);if(name.startsWith(FACTORY_BEAN_PREFIX)){
beanName = FACTORY_BEAN_PREFIX + beanName;}return beanName;}/**
* Initialize the given BeanWrapper with the custom editors registered
* with this factory. To be called for BeanWrappers that will create
* and populate bean instances.
* 初始化BeanWrapper
*/protectedvoidinitBeanWrapper(BeanWrapper bw){
bw.setConversionService(getConversionService());registerCustomEditors(bw);}/**
* Initialize the given PropertyEditorRegistry with the custom editors
* that have been registered with this BeanFactory.
* To be called for BeanWrappers that will create and populate bean
* instances, and for SimpleTypeConverter used for constructor argument
* and factory method type conversion.
* 批量註冊屬性編輯器
*/protectedvoidregisterCustomEditors(PropertyEditorRegistry registry){
PropertyEditorRegistrySupport registrySupport =(registry instanceofPropertyEditorRegistrySupport?(PropertyEditorRegistrySupport) registry : null);if(registrySupport != null){
registrySupport.useConfigValueEditors();}if(!this.propertyEditorRegistrars.isEmpty()){for(PropertyEditorRegistrar registrar :this.propertyEditorRegistrars){try{// 批量註冊到propertyEditorRegistrars
registrar.registerCustomEditors(registry);}catch(BeanCreationException ex){
Throwable rootCause = ex.getMostSpecificCause();if(rootCause instanceofBeanCurrentlyInCreationException){
BeanCreationException bce =(BeanCreationException) rootCause;
String bceBeanName = bce.getBeanName();if(bceBeanName != null &&isCurrentlyInCreation(bceBeanName)){if(logger.isDebugEnabled()){
logger.debug("PropertyEditorRegistrar ["+ registrar.getClass().getName()+"] failed because it tried to obtain currently created bean '"+
ex.getBeanName()+"': "+ ex.getMessage());}onSuppressedException(ex);continue;}}throw ex;}}}if(!this.customEditors.isEmpty()){this.customEditors.forEach((requiredType, editorClass)->
registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass)));}}/**
* Return a merged RootBeanDefinition, traversing(穿越) the parent bean definition
* if the specified bean corresponds(相應地) to a child bean definition.
*
*/protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName)throws BeansException {// Quick check on the concurrent map first, with minimal locking.
RootBeanDefinition mbd =this.mergedBeanDefinitions.get(beanName);// 緩存if(mbd != null &&!mbd.stale){return mbd;}returngetMergedBeanDefinition(beanName,getBeanDefinition(beanName));}/**
* Return a RootBeanDefinition for the given top-level bean, by merging with
* the parent if the given bean's definition is a child bean definition.
*/protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)throws BeanDefinitionStoreException {returngetMergedBeanDefinition(beanName, bd, null);}/**
* Return a RootBeanDefinition for the given bean, by merging with the
* parent if the given bean's definition is a child bean definition.
*/protected RootBeanDefinition getMergedBeanDefinition(
String beanName, BeanDefinition bd,@Nullable BeanDefinition containingBd)throws BeanDefinitionStoreException {synchronized(this.mergedBeanDefinitions){
RootBeanDefinition mbd = null;
RootBeanDefinition previous = null;// Check with full lock now in order to enforce the same merged instance.if(containingBd == null){
mbd =this.mergedBeanDefinitions.get(beanName);}if(mbd == null || mbd.stale){
previous = mbd;// 沒有父類,根據bd類型直接創建或者克隆返回if(bd.getParentName()== null){// Use copy of given root bean definition.if(bd instanceofRootBeanDefinition){
mbd =((RootBeanDefinition) bd).cloneBeanDefinition();}else{
mbd =newRootBeanDefinition(bd);}}else{// Child bean definition: needs to be merged with parent.
BeanDefinition pbd;try{
String parentBeanName =transformedBeanName(bd.getParentName());if(!beanName.equals(parentBeanName)){
pbd =getMergedBeanDefinition(parentBeanName);}else{
BeanFactory parent =getParentBeanFactory();if(parent instanceofConfigurableBeanFactory){
pbd =((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);}else{thrownewNoSuchBeanDefinitionException(parentBeanName,"Parent name '"+ parentBeanName +"' is equal to bean name '"+ beanName +"': cannot be resolved without an AbstractBeanFactory parent");}}}catch(NoSuchBeanDefinitionException ex){thrownewBeanDefinitionStoreException(bd.getResourceDescription(), beanName,"Could not resolve parent bean definition '"+ bd.getParentName()+"'", ex);}// Deep copy with overridden values.
mbd =newRootBeanDefinition(pbd);
mbd.overrideFrom(bd);}// Set default singleton scope, if not configured before.// 默認單例if(!StringUtils.hasLength(mbd.getScope())){
mbd.setScope(SCOPE_SINGLETON);}// A bean contained in a non-singleton bean cannot be a singleton itself.// Let's correct this on the fly here, since this might be the result of// parent-child merging for the outer bean, in which case the original inner bean// definition will not have inherited the merged outer bean's singleton status.if(containingBd != null &&!containingBd.isSingleton()&& mbd.isSingleton()){
mbd.setScope(containingBd.getScope());}// Cache the merged bean definition for the time being// (it might still get re-merged later on in order to pick up metadata changes)// 緩存bean的定義定義if(containingBd == null &&isCacheBeanMetadata()){this.mergedBeanDefinitions.put(beanName, mbd);}}if(previous != null){copyRelevantMergedBeanDefinitionCaches(previous, mbd);}return mbd;}}privatevoidcopyRelevantMergedBeanDefinitionCaches(RootBeanDefinition previous, RootBeanDefinition mbd){if(ObjectUtils.nullSafeEquals(mbd.getBeanClassName(), previous.getBeanClassName())&&
ObjectUtils.nullSafeEquals(mbd.getFactoryBeanName(), previous.getFactoryBeanName())&&
ObjectUtils.nullSafeEquals(mbd.getFactoryMethodName(), previous.getFactoryMethodName())){
ResolvableType targetType = mbd.targetType;
ResolvableType previousTargetType = previous.targetType;if(targetType == null || targetType.equals(previousTargetType)){
mbd.targetType = previousTargetType;
mbd.isFactoryBean = previous.isFactoryBean;
mbd.resolvedTargetType = previous.resolvedTargetType;
mbd.factoryMethodReturnType = previous.factoryMethodReturnType;
mbd.factoryMethodToIntrospect = previous.factoryMethodToIntrospect;}}}/**
* Check the given merged bean definition,
* potentially throwing validation exceptions.
* 如果是抽象的,就拋異常
*/protectedvoidcheckMergedBeanDefinition(RootBeanDefinition mbd, String beanName,@Nullable Object[] args)throws BeanDefinitionStoreException {if(mbd.isAbstract()){thrownewBeanIsAbstractException(beanName);}}/**
* Remove the merged bean definition for the specified bean,
* recreating it on next access.
* 移除bean的定義
*/protectedvoidclearMergedBeanDefinition(String beanName){
RootBeanDefinition bd =this.mergedBeanDefinitions.get(beanName);if(bd != null){
bd.stale =true;}}/**
* Clear the merged bean definition cache, removing entries for beans
* which are not considered eligible for full metadata caching yet.
* Typically triggered after changes to the original bean definitions,
* e.g. after applying a {@code BeanFactoryPostProcessor}. Note that metadata
* for beans which have already been created at this point will be kept around.
* 移除還沒創建的bean對應的bean定義
*/publicvoidclearMetadataCache(){this.mergedBeanDefinitions.forEach((beanName, bd)->{if(!isBeanEligibleForMetadataCaching(beanName)){
bd.stale =true;}});}/**
* Resolve the bean class for the specified bean definition,
* resolving a bean class name into a Class reference (if necessary)
* and storing the resolved Class in the bean definition for further use.
*/@Nullableprotected Class<?>resolveBeanClass(final RootBeanDefinition mbd, String beanName,final Class<?>... typesToMatch)throws CannotLoadBeanClassException {try{if(mbd.hasBeanClass()){// 已經解析過,直接返回return mbd.getBeanClass();}if(System.getSecurityManager()!= null){return AccessController.doPrivileged((PrivilegedExceptionAction<Class<?>>)()->doResolveBeanClass(mbd, typesToMatch),getAccessControlContext());}else{returndoResolveBeanClass(mbd, typesToMatch);}}catch(PrivilegedActionException pae){
ClassNotFoundException ex =(ClassNotFoundException) pae.getException();thrownewCannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);}catch(ClassNotFoundException ex){thrownewCannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);}catch(LinkageError err){thrownewCannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err);}}@Nullable// 根據bean定義 解析 bean的類型classprivate Class<?>doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch)throws ClassNotFoundException {
ClassLoader beanClassLoader =getBeanClassLoader();
ClassLoader dynamicLoader = beanClassLoader;boolean freshResolve =false;if(!ObjectUtils.isEmpty(typesToMatch)){// When just doing type checks (i.e. not creating an actual instance yet),// use the specified temporary class loader (e.g. in a weaving scenario).
ClassLoader tempClassLoader =getTempClassLoader();if(tempClassLoader != null){
dynamicLoader = tempClassLoader;
freshResolve =true;if(tempClassLoader instanceofDecoratingClassLoader){
DecoratingClassLoader dcl =(DecoratingClassLoader) tempClassLoader;for(Class<?> typeToMatch : typesToMatch){// 臨時加載器排序這些類型
dcl.excludeClass(typeToMatch.getName());}}}}
String className = mbd.getBeanClassName();if(className != null){// bean的表達式解析器解析
Object evaluated =evaluateBeanDefinitionString(className, mbd);// 類名不一樣if(!className.equals(evaluated)){// A dynamically resolved expression, supported as of 4.2...// 是class直接返回if(evaluated instanceofClass){return(Class<?>) evaluated;}elseif(evaluated instanceofString){// 字符串freshResolve爲true
className =(String) evaluated;
freshResolve =true;}else{thrownewIllegalStateException("Invalid class name expression result: "+ evaluated);}}if(freshResolve){// When resolving against a temporary class loader, exit early in order// to avoid storing the resolved Class in the bean definition.// 類命一樣,且是字符串if(dynamicLoader != null){try{// 類加載器加載return dynamicLoader.loadClass(className);}catch(ClassNotFoundException ex){if(logger.isTraceEnabled()){
logger.trace("Could not load class ["+ className +"] from "+ dynamicLoader +": "+ ex);}}}// 沒有類加載器return ClassUtils.forName(className, dynamicLoader);}}// Resolve regularly, caching the result in the BeanDefinition...// 解析並緩存在bean的定義中return mbd.resolveBeanClass(beanClassLoader);}/**
* Evaluate the given String as contained in a bean definition,
* potentially resolving it as an expression.
*/@Nullableprotected Object evaluateBeanDefinitionString(@Nullable String value,@Nullable BeanDefinition beanDefinition){// bean的表達式解析器爲空直接返回valueif(this.beanExpressionResolver == null){return value;}
Scope scope = null;// 不爲空,取scope,去解析if(beanDefinition != null){
String scopeName = beanDefinition.getScope();if(scopeName != null){
scope =getRegisteredScope(scopeName);}}returnthis.beanExpressionResolver.evaluate(value,newBeanExpressionContext(this, scope));}/**
* Predict the eventual bean type (of the processed bean instance) for the
* specified bean. Called by #getType and #isTypeMatch.
* Does not need to handle FactoryBeans specifically, since it is only
* supposed to operate on the raw bean type.
* This implementation is simplistic in that it is not able to
* handle factory methods and InstantiationAwareBeanPostProcessors.
* It only predicts the bean type correctly for a standard bean.
* To be overridden in subclasses, applying more sophisticated type detection.
* 預測bean的類型
*/@Nullableprotected Class<?>predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch){// 如果targetType不爲空,直接返回
Class<?> targetType = mbd.getTargetType();if(targetType != null){return targetType;}if(mbd.getFactoryMethodName()!= null){return null;}returnresolveBeanClass(mbd, beanName, typesToMatch);}/**
* Check whether the given bean is defined as a {@link FactoryBean}.
*/protectedbooleanisFactoryBean(String beanName, RootBeanDefinition mbd){
Boolean result = mbd.isFactoryBean;if(result == null){// 獲取解析後的類型
Class<?> beanType =predictBeanType(beanName, mbd, FactoryBean.class);// 如果解析的類型不爲空,且是FactoryBean,返回true
result =(beanType != null && FactoryBean.class.isAssignableFrom(beanType));
mbd.isFactoryBean = result;}return result;}/**
* Determine the bean type for the given FactoryBean definition, as far as possible.
* Only called if there is no singleton instance registered for the target bean
* already. Implementations are only allowed to instantiate the factory bean if
* allowInit is true, otherwise they should try to determine the
* result through other means.
* If no FactoryBean#OBJECT_TYPE_ATTRIBUTE if set on the bean definition
* and allowInit is true, the default implementation will create
* the FactoryBean via getBean to call its getObjectType method.
* Subclasses are encouraged to optimize this, typically by inspecting the generic
* signature of the factory bean class or the factory method that creates it. If
* subclasses do instantiate the FactoryBean, they should consider trying the
* getObjectType method without fully populating the bean. If this fails, a
* full FactoryBean creation as performed by this implementation should be used as
* fallback.
* 通過beanName和定義獲取FactoryBean的類型
*/protected ResolvableType getTypeForFactoryBean(String beanName, RootBeanDefinition mbd,boolean allowInit){
ResolvableType result =getTypeForFactoryBeanFromAttributes(mbd);if(result != ResolvableType.NONE){return result;}if(allowInit && mbd.isSingleton()){try{
FactoryBean<?> factoryBean =doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null,true);
Class<?> objectType =getTypeForFactoryBean(factoryBean);return(objectType != null)? ResolvableType.forClass(objectType): ResolvableType.NONE;}catch(BeanCreationException ex){if(ex.contains(BeanCurrentlyInCreationException.class)){
logger.trace(LogMessage.format("Bean currently in creation on FactoryBean type check: %s", ex));}elseif(mbd.isLazyInit()){
logger.trace(LogMessage.format("Bean creation exception on lazy FactoryBean type check: %s", ex));}else{
logger.debug(LogMessage.format("Bean creation exception on non-lazy FactoryBean type check: %s", ex));}onSuppressedException(ex);}}return ResolvableType.NONE;}/**
* Determine the bean type for a FactoryBean by inspecting its attributes for a
* FactoryBean#OBJECT_TYPE_ATTRIBUTE value.
*/
ResolvableType getTypeForFactoryBeanFromAttributes(AttributeAccessor attributes){
Object attribute = attributes.getAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE);if(attribute instanceofResolvableType){return(ResolvableType) attribute;}if(attribute instanceofClass){return ResolvableType.forClass((Class<?>) attribute);}return ResolvableType.NONE;}/**
* Determine the bean type for the given FactoryBean definition, as far as possible.
* Only called if there is no singleton instance registered for the target bean already.
* <p>The default implementation creates the FactoryBean via getBean
* to call its getObjectType method. Subclasses are encouraged to optimize
* this, typically by just instantiating the FactoryBean but not populating it yet,
* trying whether its getObjectType method already returns a type.
* If no type found, a full FactoryBean creation as performed by this implementation
* should be used as fallback.
*/@Nullable@Deprecatedprotected Class<?>getTypeForFactoryBean(String beanName, RootBeanDefinition mbd){returngetTypeForFactoryBean(beanName, mbd,true).resolve();}/**
* Mark the specified bean as already created (or about to be created).
* 如果沒有加入到alreadyCreated,就清除當前bean的定義,並加入到alreadyCreated
*/protectedvoidmarkBeanAsCreated(String beanName){if(!this.alreadyCreated.contains(beanName)){synchronized(this.mergedBeanDefinitions){if(!this.alreadyCreated.contains(beanName)){// Let the bean definition get re-merged now that we're actually creating// the bean... just in case some of its metadata changed in the meantime.clearMergedBeanDefinition(beanName);this.alreadyCreated.add(beanName);}}}}/**
* Perform appropriate cleanup of cached metadata after bean creation failed.
* 創建失敗後,從alreadyCreated移除
*/protectedvoidcleanupAfterBeanCreationFailure(String beanName){synchronized(this.mergedBeanDefinitions){this.alreadyCreated.remove(beanName);}}/**
* Determine whether the specified bean is eligible for having
* its bean definition metadata cached.
* 是否已創建
*/protectedbooleanisBeanEligibleForMetadataCaching(String beanName){returnthis.alreadyCreated.contains(beanName);}/**
* Remove the singleton instance (if any) for the given bean name,
* but only if it hasn't been used for other purposes than type checking.
* 移除沒有在alreadyCreated中的單例
*/protectedbooleanremoveSingletonIfCreatedForTypeCheckOnly(String beanName){if(!this.alreadyCreated.contains(beanName)){removeSingleton(beanName);returntrue;}else{returnfalse;}}/**
* Check whether this factory's bean creation phase already started,
* i.e. whether any bean has been marked as created in the meantime.
* 是否已經有bean開始創建了,alreadyCreated爲空,說明還沒創建,不爲空,已經創建
*/protectedbooleanhasBeanCreationStarted(){return!this.alreadyCreated.isEmpty();}/**
* Get the object for the given bean instance, either the bean
* instance itself or its created object in case of a FactoryBean.
* 如果是非FactoryBean的直接返回,如果是FactoryBean的則處理
*/protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName,@Nullable RootBeanDefinition mbd){// Don't let calling code try to dereference the factory if the bean isn't a factory.// 如果beanname是&開頭的,這個bean必須是FactoryBean類型if(BeanFactoryUtils.isFactoryDereference(name)){if(beanInstance instanceofNullBean){return beanInstance;}if(!(beanInstance instanceofFactoryBean)){thrownewBeanIsNotAFactoryException(beanName, beanInstance.getClass());}if(mbd != null){
mbd.isFactoryBean =true;}return beanInstance;}// Now we have the bean instance, which may be a normal bean or a FactoryBean.// If it's a FactoryBean, we use it to create a bean instance, unless the// caller actually wants a reference to the factory.// 普通bean或者beanname是&開頭的,返回beanInstanceif(!(beanInstance instanceofFactoryBean)){return beanInstance;}// 是FactoryBean但是沒有&開頭的
Object object = null;if(mbd != null){
mbd.isFactoryBean =true;}else{// bean的定義信息是空的,從緩存中拿
object =getCachedObjectForFactoryBean(beanName);}if(object == null){//緩存不存在// Return bean instance from factory.
FactoryBean<?> factory =(FactoryBean<?>) beanInstance;// Caches object obtained from FactoryBean if it is a singleton.// mdb爲空,並且已經實例化過if(mbd == null &&containsBeanDefinition(beanName)){
mbd =getMergedLocalBeanDefinition(beanName);}// 是否是用戶定義的,而不是程序本身定義的boolean synthetic =(mbd != null && mbd.isSynthetic());
object =getObjectFromFactoryBean(factory, beanName,!synthetic);}return object;}/**
* Determine whether the given bean name is already in use within this factory,
* i.e. whether there is a local bean or alias registered under this name or
* an inner bean created with this name.
* 從別名、bean的定義、依賴判斷beanName是否已使用
*/publicbooleanisBeanNameInUse(String beanName){returnisAlias(beanName)||containsLocalBean(beanName)||hasDependentBean(beanName);}/**
* Determine whether the given bean requires destruction on shutdown.
* <p>The default implementation checks the DisposableBean interface as well as
* a specified destroy method and registered DestructionAwareBeanPostProcessors.
* 確定給定的bean在關閉時是否需要銷燬
*/protectedbooleanrequiresDestruction(Object bean, RootBeanDefinition mbd){return(bean.getClass()!= NullBean.class&&(DisposableBeanAdapter.hasDestroyMethod(bean, mbd)||(hasDestructionAwareBeanPostProcessors()&&
DisposableBeanAdapter.hasApplicableProcessors(bean,getBeanPostProcessors()))));}/**
* Add the given bean to the list of disposable beans in this factory,
* registering its DisposableBean interface and/or the given destroy method
* to be called on factory shutdown (if applicable). Only applies to singletons.
* 根據scope註冊需要銷燬的bean
*/protectedvoidregisterDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd){
AccessControlContext acc =(System.getSecurityManager()!= null ?getAccessControlContext(): null);// 不是原型且需要銷燬if(!mbd.isPrototype()&&requiresDestruction(bean, mbd)){if(mbd.isSingleton()){// Register a DisposableBean implementation that performs all destruction// work for the given bean: DestructionAwareBeanPostProcessors,// DisposableBean interface, custom destroy method.// 單例模式下需要銷燬的beanregisterDisposableBean(beanName,newDisposableBeanAdapter(bean, beanName, mbd,getBeanPostProcessors(), acc));}else{// A bean with a custom scope... // 自定義scope的處理
Scope scope =this.scopes.get(mbd.getScope());if(scope == null){thrownewIllegalStateException("No Scope registered for scope name '"+ mbd.getScope()+"'");}
scope.registerDestructionCallback(beanName,newDisposableBeanAdapter(bean, beanName, mbd,getBeanPostProcessors(), acc));}}}//---------------------------------------------------------------------// Abstract methods to be implemented by subclasses 抽象的模板方法//---------------------------------------------------------------------/**
* Check if this bean factory contains a bean definition with the given name.
* Does not consider any hierarchy this factory may participate in.
* Invoked by {@code containsBean} when no cached singleton instance is found.
* <p>Depending on the nature of the concrete bean factory implementation,
* this operation might be expensive (for example, because of directory lookups
* in external registries). However, for listable bean factories, this usually
* just amounts to a local hash lookup: The operation is therefore part of the
* public interface there. The same implementation can serve for both this
* template method and the public interface method in that case.
*/protectedabstractbooleancontainsBeanDefinition(String beanName);/**
* Return the bean definition for the given bean name.
* Subclasses should normally implement caching, as this method is invoked
* by this class every time bean definition metadata is needed.
* <p>Depending on the nature of the concrete bean factory implementation,
* this operation might be expensive (for example, because of directory lookups
* in external registries). However, for listable bean factories, this usually
* just amounts to a local hash lookup: The operation is therefore part of the
* public interface there. The same implementation can serve for both this
* template method and the public interface method in that case.
*/protectedabstract BeanDefinition getBeanDefinition(String beanName)throws BeansException;/**
* Create a bean instance for the given merged bean definition (and arguments).
* The bean definition will already have been merged with the parent definition
* in case of a child definition.
* <p>All bean retrieval methods delegate to this method for actual bean creation.
*/protectedabstract Object createBean(String beanName, RootBeanDefinition mbd,@Nullable Object[] args)throws BeanCreationException;}