AbstractBeanFactory抽象類,繼承了FactoryBeanRegistrySupport及實現了ConfigurableBeanFactory接口。express
// 父類容器 private BeanFactory parentBeanFactory; // 類加載器 private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); // 臨時加載器 private ClassLoader tempClassLoader; // bean的元數據緩存 private boolean cacheBeanMetadata = true; // bean的表達式解析器 private BeanExpressionResolver beanExpressionResolver; // 類型轉換器 private ConversionService conversionService; // 屬性編輯器 private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet<>(4); // 類的屬性編輯器 private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>(4); // 類型轉換器 private TypeConverter typeConverter; // 爲嵌入的值(如註釋屬性)添加字符串解析器 private final List<StringValueResolver> embeddedValueResolvers = new CopyOnWriteArrayList<>(); // 後置處理器 private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>(); // InstantiationAwareBeanPostProcessors是否已註冊 private volatile boolean hasInstantiationAwareBeanPostProcessors; // DestructionAwareBeanPostProcessors是否已註冊 private volatile boolean hasDestructionAwareBeanPostProcessors; // 做用域 private final Map<String, Scope> scopes = new LinkedHashMap<>(8); // 提供安全做用域 private SecurityContextProvider securityContextProvider; // 合併後的BeanDefinition private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<>(256); // bean實例是否已建立 private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256)); // 本地緩存,正在建立的多例bean。這邊用本地線程,是由於其餘線程建立bean與當前線程不衝突 private final ThreadLocal<Object> prototypesCurrentlyInCreation = new NamedThreadLocal<>("Prototype beans currently in creation");
構造函數,父類容器可做爲參數傳入segmentfault
public AbstractBeanFactory() { } public AbstractBeanFactory(@Nullable BeanFactory parentBeanFactory) { this.parentBeanFactory = parentBeanFactory; }
實際上都是調用doGetBean的方法緩存
@Override public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); } @Override public <T> T getBean(String name, Class<T> requiredType) throws BeansException { return doGetBean(name, requiredType, null, false); } @Override public Object getBean(String name, Object... args) throws BeansException { return doGetBean(name, null, args, false); } public <T> T getBean(String name, @Nullable Class<T> requiredType, @Nullable Object... args) throws BeansException { return doGetBean(name, requiredType, args, false); }
doGetBean有四個參數:安全
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, @Nullable final 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,而直接建立bean if (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或者是多例的狀況或者有參數的狀況 // 建立過Prototype的bean,會循環引用,拋出異常,單例才嘗試解決循環依賴的問題 if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } // Check if bean definition exists in this factory. BeanFactory parentBeanFactory = getParentBeanFactory(); // 父容器存在,本地沒有當前beanName,從父容器取 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. // 處理後,若是是加&,就補上& String nameToLookup = originalBeanName(name); if (parentBeanFactory instanceof AbstractBeanFactory) { return ((AbstractBeanFactory) parentBeanFactory).doGetBean( nameToLookup, requiredType, args, typeCheckOnly); } else if (args != null) { // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } else if (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中 markBeanAsCreated(beanName); } try { // 獲取BeanDefinition final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // 抽象類檢查 checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on. // 若是有依賴的狀況,先初始化依賴的bean String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { // 檢查是否循環依賴,a依賴b,b依賴a。包括傳遞的依賴,好比a依賴b,b依賴c,c依賴a if (isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } // 註冊依賴關係 registerDependentBean(dep, beanName); try { // 初始化依賴的bean getBean(dep); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } } // Create bean instance. // 若是是單例 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { try { // 建立bean return createBean(beanName, mbd, args); } 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); } else if (mbd.isPrototype()) { // 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 { String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, () -> { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } } } catch (BeansException ex) { cleanupAfterBeanCreationFailure(beanName); throw ex; } } // Check if required type matches the type of the actual bean instance. if (requiredType != null && !requiredType.isInstance(bean)) { try { T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType); if (convertedBean == null) { throw new BeanNotOfRequiredTypeException(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); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; }
是否已經建立bean或者定義好了bean,包括當前容器以及父容器app
public boolean containsBean(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))); }
指定beanName是不是單例,包括普通的bean和FactoryBean,包括當前容器以及父容器less
public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); // 若是已經實例化了 Object beanInstance = getSingleton(beanName, false); if (beanInstance != null) { if (beanInstance instanceof FactoryBean) { // 是FactoryBean類型,name要&開頭或者FactoryBean中isSingleton方法返回爲true return (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)) { return true; } // 若是是單例,可是name不是&開頭,就從新獲取factoryBean,再判斷是不是單例 FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); return factoryBean.isSingleton(); } else { // 若是不是FactoryBean,就不能是&開頭 return !BeanFactoryUtils.isFactoryDereference(name); } } else { return false; } }
指定beanName是不是多例,包括普通的bean和FactoryBean,包括當前容器以及父容器編輯器
public boolean isPrototype(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,返回true return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd)); } // Singleton or scoped - not a prototype. // However, FactoryBean may still produce a prototype object... // 若是不是Prototype,且是&開頭,&開頭就是FactoryBean,FactoryBean是單例的,因此是返回false if (BeanFactoryUtils.isFactoryDereference(name)) { return false; } // 若是是FactoryBean,判斷是否有Singleton或者Prototype if (isFactoryBean(beanName, mbd)) { final FactoryBean<?> fb = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); if (System.getSecurityManager() != null) { return AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> ((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) || !fb.isSingleton()), getAccessControlContext()); } else { return ((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) || !fb.isSingleton()); } } else { return false; } }
指定的beanName是否與類型匹配ide
public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); // Check manually registered singletons. // 獲取單例 Object beanInstance = getSingleton(beanName, false); // 不爲空而且不是NullBean類型 if (beanInstance != null && beanInstance.getClass() != NullBean.class) { if (beanInstance instanceof FactoryBean) { if (!BeanFactoryUtils.isFactoryDereference(name)) { // 不是&開頭,獲取FactoryBean的getObjectType類型,再來比較 Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance); return (type != null && typeToMatch.isAssignableFrom(type)); } else { // name是&開頭,直接判斷類型FactoryBean return typeToMatch.isInstance(beanInstance); } } // 普通bean,且沒有&開頭 else if (!BeanFactoryUtils.isFactoryDereference(name)) { if (typeToMatch.isInstance(beanInstance)) { // Direct match for exposed instance? return true; } // 泛型且有beanName的定義 else if (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)) { return false; } if (typeToMatch.isAssignableFrom(targetType)) { return true; } } ResolvableType resolvableType = mbd.targetType; if (resolvableType == null) { resolvableType = mbd.factoryMethodReturnType; } return (resolvableType != null && typeToMatch.isAssignableFrom(resolvableType)); } } return false; } // 已經建立了,可是沒有bean的定義,說明是空的註冊進來 else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) { // null instance registered return false; } // 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. RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); Class<?> classToMatch = typeToMatch.resolve(); if (classToMatch == null) { classToMatch = FactoryBean.class; } Class<?>[] typesToMatch = (FactoryBean.class == classToMatch ? new Class<?>[] {classToMatch} : new Class<?>[] {FactoryBean.class, classToMatch}); // Check decorated bean definition, if any: We assume it'll be easier // to determine the decorated bean's type than the proxy's type. BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) { RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd); Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd, typesToMatch); if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return typeToMatch.isAssignableFrom(targetClass); } } Class<?> beanType = predictBeanType(beanName, mbd, typesToMatch); if (beanType == null) { return false; } // Check bean class whether we're dealing with a FactoryBean. if (FactoryBean.class.isAssignableFrom(beanType)) { if (!BeanFactoryUtils.isFactoryDereference(name) && beanInstance == null) { // If it's a FactoryBean, we want to look at what it creates, not the factory class. beanType = getTypeForFactoryBean(beanName, mbd); if (beanType == null) { return false; } } } else if (BeanFactoryUtils.isFactoryDereference(name)) { // 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. beanType = predictBeanType(beanName, mbd, FactoryBean.class); if (beanType == null || !FactoryBean.class.isAssignableFrom(beanType)) { return false; } } ResolvableType resolvableType = mbd.targetType; if (resolvableType == null) { resolvableType = mbd.factoryMethodReturnType; } if (resolvableType != null && resolvableType.resolve() == beanType) { return typeToMatch.isAssignableFrom(resolvableType); } return typeToMatch.isAssignableFrom(beanType); } public boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException { // 類型轉換後調用上面的方法 return isTypeMatch(name, ResolvableType.forRawClass(typeToMatch)); }
獲取指定beanName的類型函數
public Class<?> getType(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); // Check manually registered singletons. Object beanInstance = getSingleton(beanName, false); // 已經實例化而且不是NullBean if (beanInstance != null && beanInstance.getClass() != NullBean.class) { // 若是是FactoryBean,且沒有&,說明是取FactoryBean的getObjectType類型 if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { return getTypeForFactoryBean((FactoryBean<?>) beanInstance); } else { // 直接返回類型 return beanInstance.getClass(); } } // No singleton instance found -> check bean definition. // 沒有實例過,從父容器看看有沒有實例化 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.getType(originalBeanName(name)); } // 都沒有實例化,從定義裏查找 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // Check decorated bean definition, if any: We assume it'll be easier // to determine the decorated bean's type than the proxy's type. BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) { RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd); Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd); if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return targetClass; } } Class<?> beanClass = predictBeanType(beanName, mbd); // Check bean class whether we're dealing with a FactoryBean. if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) { if (!BeanFactoryUtils.isFactoryDereference(name)) { // If it's a FactoryBean, we want to look at what it creates, not at the factory class. return getTypeForFactoryBean(beanName, mbd); } else { return beanClass; } } else { return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null); } }
public String[] getAliases(String name) { String beanName = transformedBeanName(name); List<String> aliases = new ArrayList<>(); // 若是有&解析後要再加回去 boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX); String fullBeanName = beanName; if (factoryPrefix) { fullBeanName = FACTORY_BEAN_PREFIX + beanName; } if (!fullBeanName.equals(name)) { aliases.add(fullBeanName); } String[] retrievedAliases = super.getAliases(beanName); for (String retrievedAlias : retrievedAliases) { String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") + retrievedAlias; if (!alias.equals(name)) { aliases.add(alias); } } // 沒實例化過且沒有bean的定義,從父類查找 if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) { BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null) { aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName))); } } return StringUtils.toStringArray(aliases); }
獲取父容器post
public BeanFactory getParentBeanFactory() { return this.parentBeanFactory; }
設置父容器
public void setParentBeanFactory(@Nullable BeanFactory parentBeanFactory) { // 只能設置一個,不能修改 if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) { throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory); } this.parentBeanFactory = parentBeanFactory; }
當前容器是否有指定的bean
public boolean containsLocalBean(String name) { String beanName = transformedBeanName(name); return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) && (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName))); }
類加載器、臨時加載器
// 設置類加載器 public void setBeanClassLoader(@Nullable ClassLoader beanClassLoader) { this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader()); } // 獲取類加載器 public ClassLoader getBeanClassLoader() { return this.beanClassLoader; } // 設置臨時加載器,若是涉及到加載時編織,一般只指定一個臨時類裝入器,以確保實際的bean類被儘量延遲地裝入 public void setTempClassLoader(@Nullable ClassLoader tempClassLoader) { this.tempClassLoader = tempClassLoader; } // 獲取臨時加載器 public ClassLoader getTempClassLoader() { return this.tempClassLoader; }
bean的元數據緩存,默認爲true。若是爲false,每次建立bean都要從類加載器獲取信息
// 設置是否緩存 public void setCacheBeanMetadata(boolean cacheBeanMetadata) { this.cacheBeanMetadata = cacheBeanMetadata; } // 獲取是否緩存 public boolean isCacheBeanMetadata() { return this.cacheBeanMetadata; }
bean的表達式解析器
// 設置表達式解析器 public void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver) { this.beanExpressionResolver = resolver; } // 獲取表達式解析器 public BeanExpressionResolver getBeanExpressionResolver() { return this.beanExpressionResolver; }
類型轉換器
// 設置類型轉換器 public void setConversionService(@Nullable ConversionService conversionService) { this.conversionService = conversionService; } // 獲取類型轉換器 public ConversionService getConversionService() { return this.conversionService; }
屬性編輯器
// 添加屬性編輯器 public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) { Assert.notNull(registrar, "PropertyEditorRegistrar must not be null"); this.propertyEditorRegistrars.add(registrar); } // 獲取屬性編輯器 public Set<PropertyEditorRegistrar> getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; }
類的屬性編輯器
// 註冊類的屬性編輯器 public void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass) { Assert.notNull(requiredType, "Required type must not be null"); Assert.notNull(propertyEditorClass, "PropertyEditor class must not be null"); this.customEditors.put(requiredType, propertyEditorClass); } // 複製類的屬性編輯器 public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) { registerCustomEditors(registry); } // 獲取類的屬性編輯器 public Map<Class<?>, Class<? extends PropertyEditor>> getCustomEditors() { return this.customEditors; }
類型轉換器
// 設置類型轉換器 public void setTypeConverter(TypeConverter typeConverter) { this.typeConverter = typeConverter; } // 獲取自定義的類型轉換器,這邊直接取類型轉換器 protected TypeConverter getCustomTypeConverter() { return this.typeConverter; } // 獲取類型轉換器 public TypeConverter getTypeConverter() { TypeConverter customConverter = getCustomTypeConverter(); if (customConverter != null) { return customConverter; } else { // Build default TypeConverter, registering custom editors. // 沒有設值就初始化一個SimpleTypeConverter SimpleTypeConverter typeConverter = new SimpleTypeConverter(); typeConverter.setConversionService(getConversionService()); registerCustomEditors(typeConverter); return typeConverter; } }
爲嵌入的值(如註釋屬性)添加字符串解析器
// 添加 public void addEmbeddedValueResolver(StringValueResolver valueResolver) { Assert.notNull(valueResolver, "StringValueResolver must not be null"); this.embeddedValueResolvers.add(valueResolver); } // 是否有 public boolean hasEmbeddedValueResolver() { return !this.embeddedValueResolvers.isEmpty(); } // 解析給定的嵌入值 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; }
// 增長後置處理器 public void addBeanPostProcessor(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 // 若是是下面兩個類型,標誌位就設置true if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) { this.hasInstantiationAwareBeanPostProcessors = true; } if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) { this.hasDestructionAwareBeanPostProcessors = true; } // Add to end of list this.beanPostProcessors.add(beanPostProcessor); } // 獲取後置處理器的個數 public int getBeanPostProcessorCount() { return this.beanPostProcessors.size(); } // 獲取後置處理器 public List<BeanPostProcessor> getBeanPostProcessors() { return this.beanPostProcessors; }
這兩個的值在addBeanPostProcessor時設置
protected boolean hasInstantiationAwareBeanPostProcessors() { return this.hasInstantiationAwareBeanPostProcessors; } protected boolean hasDestructionAwareBeanPostProcessors() { return this.hasDestructionAwareBeanPostProcessors; }
做用域
// 註冊做用域 public void registerScope(String scopeName, Scope scope) { Assert.notNull(scopeName, "Scope identifier must not be null"); Assert.notNull(scope, "Scope must not be null"); // 單例和多例,不容許再註冊 if (SCOPE_SINGLETON.equals(scopeName) || SCOPE_PROTOTYPE.equals(scopeName)) { throw new IllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'"); } 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 + "]"); } } } // 獲取做用域,除了單例和多例,這兩個註冊的時候會報錯 public String[] getRegisteredScopeNames() { return StringUtils.toStringArray(this.scopes.keySet()); } // 經過名稱獲取做用域 public Scope getRegisteredScope(String scopeName) { Assert.notNull(scopeName, "Scope identifier must not be null"); return this.scopes.get(scopeName); }
// 設置SecurityContextProvider public void setSecurityContextProvider(SecurityContextProvider securityProvider) { this.securityContextProvider = securityProvider; } // 獲取安全做用域 public AccessControlContext getAccessControlContext() { return (this.securityContextProvider != null ? this.securityContextProvider.getAccessControlContext() : AccessController.getContext()); }
配置複製。複製內容包括全部標準配置設置以及beanpostprocessor、做用域和特定於工廠的內部設置。不該該包含任何實際bean定義的元數據,例如BeanDefinition對象和bean名稱別名。
public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { Assert.notNull(otherFactory, "BeanFactory must not be null"); setBeanClassLoader(otherFactory.getBeanClassLoader()); setCacheBeanMetadata(otherFactory.isCacheBeanMetadata()); setBeanExpressionResolver(otherFactory.getBeanExpressionResolver()); setConversionService(otherFactory.getConversionService()); if (otherFactory instanceof AbstractBeanFactory) { 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)); } } }
合併bean的定義,包括父類繼承下來的
public BeanDefinition getMergedBeanDefinition(String name) throws BeansException { String beanName = transformedBeanName(name); // Efficiently check whether bean definition exists in this factory. // 若是當前容器沒有,且父類是ConfigurableBeanFactory類型,去父類找 if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) { return ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(beanName); } // Resolve merged bean definition locally. // 去本地找 return getMergedLocalBeanDefinition(beanName); }
是不是FactoryBean類型
public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException { // 獲取beanName String beanName = transformedBeanName(name); // 獲取實例 Object beanInstance = getSingleton(beanName, false); // 已經實例化直接判斷 if (beanInstance != null) { return (beanInstance instanceof FactoryBean); } // No singleton instance found -> check bean definition. // 沒有實例話,且父類是ConfigurableBeanFactory,從父類查找 if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) { // No bean definition found in this factory -> delegate to parent. return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name); } return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName)); }
是否正在建立的bean,包括單例和多例
public boolean isActuallyInCreation(String beanName) { return (isSingletonCurrentlyInCreation(beanName) || isPrototypeCurrentlyInCreation(beanName)); }
protected boolean isPrototypeCurrentlyInCreation(String beanName) { // 當前線程有值,說明有在建立多例 Object curVal = this.prototypesCurrentlyInCreation.get(); // 若是相等,或者在set中,說明建立的多例有包括指定的bean return (curVal != null && (curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName)))); }
多例建立前,把beanName加入到prototypesCurrentlyInCreation,若是是string,說明已加入一個,轉換爲set
protected void beforePrototypeCreation(String beanName) { Object curVal = this.prototypesCurrentlyInCreation.get(); if (curVal == null) { this.prototypesCurrentlyInCreation.set(beanName); } else if (curVal instanceof String) { Set<String> beanNameSet = new HashSet<>(2); beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } else { Set<String> beanNameSet = (Set<String>) curVal; beanNameSet.add(beanName); } }
多例建立完了,從prototypesCurrentlyInCreation移除
protected void afterPrototypeCreation(String beanName) { Object curVal = this.prototypesCurrentlyInCreation.get(); if (curVal instanceof String) { this.prototypesCurrentlyInCreation.remove(); } else if (curVal instanceof Set) { Set<String> beanNameSet = (Set<String>) curVal; beanNameSet.remove(beanName); if (beanNameSet.isEmpty()) { this.prototypesCurrentlyInCreation.remove(); } } }
銷燬bean
public void destroyBean(String beanName, Object beanInstance) { destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName)); } protected void destroyBean(String beanName, Object bean, RootBeanDefinition mbd) { new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), getAccessControlContext()).destroy(); } public void destroyScopedBean(String beanName) { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // 單例和多例不能銷燬 if (mbd.isSingleton() || mbd.isPrototype()) { throw new IllegalArgumentException( "Bean name '" + beanName + "' does not correspond to an object in a mutable scope"); } String scopeName = mbd.getScope(); // 沒有對應做用域的不能刪除 Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope SPI registered for scope name '" + scopeName + "'"); } // 若是已初始化,就調用銷燬的方法 Object bean = scope.remove(beanName); if (bean != null) { destroyBean(beanName, bean, mbd); } }
獲取beanName,有可能傳過來的是原始的beanName,有多是加了&的,有多是別名。若是是加了&的,先去除,再獲取。若是是別名,先遞歸到最原始的別名,再獲取beanName
protected String transformedBeanName(String name) { return canonicalName(BeanFactoryUtils.transformedBeanName(name)); }
獲取原始的beanName,若是有&,要加上&
protected String originalBeanName(String name) { String beanName = transformedBeanName(name); if (name.startsWith(FACTORY_BEAN_PREFIX)) { beanName = FACTORY_BEAN_PREFIX + beanName; } return beanName; }
初始化BeanWrapper
protected void initBeanWrapper(BeanWrapper bw) { bw.setConversionService(getConversionService()); registerCustomEditors(bw); }
批量註冊
protected void registerCustomEditors(PropertyEditorRegistry registry) { PropertyEditorRegistrySupport registrySupport = (registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null); if (registrySupport != null) { registrySupport.useConfigValueEditors(); } if (!this.propertyEditorRegistrars.isEmpty()) { for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) { try { // 批量註冊到propertyEditorRegistrars registrar.registerCustomEditors(registry); } catch (BeanCreationException ex) { Throwable rootCause = ex.getMostSpecificCause(); if (rootCause instanceof BeanCurrentlyInCreationException) { 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()) { // 批量註冊customEditors this.customEditors.forEach((requiredType, editorClass) -> registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass))); } }
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException { // Quick check on the concurrent map first, with minimal locking. RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName); // 已經有了,直接返回 if (mbd != null) { return mbd; } return getMergedBeanDefinition(beanName, getBeanDefinition(beanName)); } protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd) throws BeanDefinitionStoreException { return getMergedBeanDefinition(beanName, bd, null); } protected RootBeanDefinition getMergedBeanDefinition( String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd) throws BeanDefinitionStoreException { synchronized (this.mergedBeanDefinitions) { RootBeanDefinition mbd = 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) { // 沒有父類,根據bd類型直接建立或者克隆返回 if (bd.getParentName() == null) { // Use copy of given root bean definition. if (bd instanceof RootBeanDefinition) { mbd = ((RootBeanDefinition) bd).cloneBeanDefinition(); } else { mbd = new RootBeanDefinition(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 instanceof ConfigurableBeanFactory) { pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName); } else { throw new NoSuchBeanDefinitionException(parentBeanName, "Parent name '" + parentBeanName + "' is equal to bean name '" + beanName + "': cannot be resolved without an AbstractBeanFactory parent"); } } } catch (NoSuchBeanDefinitionException ex) { throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName, "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex); } // Deep copy with overridden values. mbd = new RootBeanDefinition(pbd); mbd.overrideFrom(bd); } // Set default singleton scope, if not configured before. // 默認單例 if (!StringUtils.hasLength(mbd.getScope())) { mbd.setScope(RootBeanDefinition.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); } } return mbd; } }
若是是抽象的,就拋異常
protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, @Nullable Object[] args) throws BeanDefinitionStoreException { if (mbd.isAbstract()) { throw new BeanIsAbstractException(beanName); } }
移除bean的定義
protected void clearMergedBeanDefinition(String beanName) { this.mergedBeanDefinitions.remove(beanName); }
移除還沒建立的bean對應的bean定義
public void clearMetadataCache() { this.mergedBeanDefinitions.keySet().removeIf(bean -> !isBeanEligibleForMetadataCaching(bean)); }
protected Class<?> resolveBeanClass(final RootBeanDefinition mbd, String beanName, final Class<?>... typesToMatch) throws CannotLoadBeanClassException { try { // 已經解析過了,直接返回 if (mbd.hasBeanClass()) { return mbd.getBeanClass(); } if (System.getSecurityManager() != null) { return AccessController.doPrivileged((PrivilegedExceptionAction<Class<?>>) () -> doResolveBeanClass(mbd, typesToMatch), getAccessControlContext()); } else { return doResolveBeanClass(mbd, typesToMatch); } } catch (PrivilegedActionException pae) { ClassNotFoundException ex = (ClassNotFoundException) pae.getException(); throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex); } catch (ClassNotFoundException ex) { throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex); } catch (LinkageError err) { throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err); } } private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch) throws ClassNotFoundException { 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 instanceof DecoratingClassLoader) { 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 instanceof Class) { return (Class<?>) evaluated; } // 字符串freshResolve爲true else if (evaluated instanceof String) { className = (String) evaluated; freshResolve = true; } else { throw new IllegalStateException("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); }
protected Object evaluateBeanDefinitionString(@Nullable String value, @Nullable BeanDefinition beanDefinition) { // bean的表達式解析器爲空直接返回value if (this.beanExpressionResolver == null) { return value; } // 不爲空,取scope,去解析 Scope scope = null; if (beanDefinition != null) { String scopeName = beanDefinition.getScope(); if (scopeName != null) { scope = getRegisteredScope(scopeName); } } return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope)); }
預測bean的類型
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) { // 若是targetType不爲空,直接返回 Class<?> targetType = mbd.getTargetType(); if (targetType != null) { return targetType; } if (mbd.getFactoryMethodName() != null) { return null; } return resolveBeanClass(mbd, beanName, typesToMatch); }
protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) { // 獲取解析後的類型 Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class); // 若是解析的類型不爲空,且是FactoryBean,返回true return (beanType != null && FactoryBean.class.isAssignableFrom(beanType)); }
// 經過beanName和定義獲取FactoryBean的類型
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) { if (!mbd.isSingleton()) { return null; } try { FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true); return getTypeForFactoryBean(factoryBean); } catch (BeanCreationException ex) { if (ex.contains(BeanCurrentlyInCreationException.class)) { if (logger.isTraceEnabled()) { logger.trace("Bean currently in creation on FactoryBean type check: " + ex); } } else if (mbd.isLazyInit()) { if (logger.isTraceEnabled()) { logger.trace("Bean creation exception on lazy FactoryBean type check: " + ex); } } else { if (logger.isDebugEnabled()) { logger.debug("Bean creation exception on non-lazy FactoryBean type check: " + ex); } } onSuppressedException(ex); return null; } }
若是沒有加入到alreadyCreated,就清除當前bean的定義,並加入到alreadyCreated
protected void markBeanAsCreated(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); } } } }
建立失敗後,從alreadyCreated移除
protected void cleanupAfterBeanCreationFailure(String beanName) { synchronized (this.mergedBeanDefinitions) { this.alreadyCreated.remove(beanName); } }
是否已建立
protected boolean isBeanEligibleForMetadataCaching(String beanName) { return this.alreadyCreated.contains(beanName); }
移除沒有在alreadyCreated中的單例
protected boolean removeSingletonIfCreatedForTypeCheckOnly(String beanName) { if (!this.alreadyCreated.contains(beanName)) { removeSingleton(beanName); return true; } else { return false; } }
是否已經有bean開始建立了,alreadyCreated爲空,說明還沒建立,不爲空,已經建立
protected boolean hasBeanCreationStarted() { return !this.alreadyCreated.isEmpty(); }
若是是非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 instanceof NullBean) { return beanInstance; } if (!(beanInstance instanceof FactoryBean)) { throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass()); } } // 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是&開頭的,返回beanInstance if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) { return beanInstance; } // 是FactoryBean可是沒有&開頭的 Object object = null; if (mbd == null) { // 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);//返回factory的getObject方法 } return object; }
從別名、bean的定義、依賴判斷beanName是否已使用
public boolean isBeanNameInUse(String beanName) { return isAlias(beanName) || containsLocalBean(beanName) || hasDependentBean(beanName); }
肯定給定的bean在關閉時是否須要銷燬
protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) { return (bean.getClass() != NullBean.class && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() && DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors())))); }
根據scope註冊須要銷燬的bean
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) { AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null); // 不是多例且須要銷燬 if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) { if (mbd.isSingleton()) { // Register a DisposableBean implementation that performs all destruction // work for the given bean: DestructionAwareBeanPostProcessors, // DisposableBean interface, custom destroy method. // 單例模式下須要銷燬的bean registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } else { // A bean with a custom scope... // 自定義scope的處理 Scope scope = this.scopes.get(mbd.getScope()); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'"); } scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } } }
是否已有指定bean的bean定義
根據指定的bean獲取bean的定義
建立bean