上一篇分析了BeanFactory體系的2個類,SimpleAliasRegistry和DefaultSingletonBeanRegistry—— Spring源碼分析——BeanFactory體系之抽象類、類分析(一),今天繼續分析。html
1、工廠Bean註冊支持——FactoryBeanRegistrySupportjava
廢話很少說,直接看我註釋的源碼:spring
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.support; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCurrentlyInCreationException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.FactoryBeanNotInitializedException; /** * Support base class for singleton registries which need to handle * {@link org.springframework.beans.factory.FactoryBean} instances, * integrated with {@link DefaultSingletonBeanRegistry}'s singleton management. * * <p>Serves as base class for {@link AbstractBeanFactory}. * * @author Juergen Hoeller * @since 2.5.1 */ public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry { /** 工廠Bean生產的單例的集合: FactoryBean name --> object */ private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<String, Object>(16); //返回指定FactoryBean的類型 protected Class getTypeForFactoryBean(final FactoryBean factoryBean) { try { if (System.getSecurityManager() != null) {//若是當前系統存在安全管理器 return AccessController.doPrivileged(new PrivilegedAction<Class>() {//那麼返回factoryBean的類型這個操做不作權限檢查,直接調用 public Class run() { return factoryBean.getObjectType(); } }, getAccessControlContext()); } else {//不存在安全管理器,就直接調用! return factoryBean.getObjectType(); } } catch (Throwable ex) { logger.warn("FactoryBean threw exception from getObjectType, despite the contract saying " + "that it should return null if the type of its object cannot be determined yet", ex); return null; } } //根據FactoryBean名,返回其生產的Object,從緩存中取 protected Object getCachedObjectForFactoryBean(String beanName) { Object object = this.factoryBeanObjectCache.get(beanName); return (object != NULL_OBJECT ? object : null); } //從工廠Bean中取實例,實際調用下面的doGetObjectFromFactoryBean方法。 protected Object getObjectFromFactoryBean(FactoryBean factory, String beanName, boolean shouldPostProcess) { if (factory.isSingleton() && containsSingleton(beanName)) {//若工廠是單例,且本容器包含beanName對應的單例類 synchronized (getSingletonMutex()) {//以全部的單例集合爲鎖 Object object = this.factoryBeanObjectCache.get(beanName);//根據beanName從factoryBeanObjectCache中取 if (object == null) {//若取不到 object = doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess); this.factoryBeanObjectCache.put(beanName, (object != null ? object : NULL_OBJECT));//放進factoryBeanObjectCache } return (object != NULL_OBJECT ? object : null); } } else {//不然,直接 return doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess); } } //從工廠Bean中取實例 private Object doGetObjectFromFactoryBean( final FactoryBean factory, final String beanName, final boolean shouldPostProcess) throws BeanCreationException { Object object; //跟getTypeForFactoryBean的實現同樣。 try { if (System.getSecurityManager() != null) {//若系統存在安全管理器 AccessControlContext acc = getAccessControlContext();//獲得當前容器的安全訪問上下文 try {//返回factoryBean的類型這個操做不作權限檢查,直接調用 object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { return factory.getObject(); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else {//不然直接取 object = factory.getObject(); } } catch (FactoryBeanNotInitializedException ex) { throw new BeanCurrentlyInCreationException(beanName, ex.toString()); } catch (Throwable ex) { throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex); } //若是從beanFactory取不到,且這個實例即將被建立,拋出異常 if (object == null && isSingletonCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException( beanName, "FactoryBean which is currently in creation returned null from getObject"); } //若取不到,且這個實例容許前處理 if (object != null && shouldPostProcess) { try { object = postProcessObjectFromFactoryBean(object, beanName);//這裏簡單返回,前處理的功能留給子類重寫 } catch (Throwable ex) { throw new BeanCreationException(beanName, "Post-processing of the FactoryBean's object failed", ex); } } return object; } //這裏簡單返回Object,留給子類重寫 protected Object postProcessObjectFromFactoryBean(Object object, String beanName) throws BeansException { return object; } //若是這個Object是FactoryBean類型,就轉換成FactoryBean返回 protected FactoryBean getFactoryBean(String beanName, Object beanInstance) throws BeansException { if (!(beanInstance instanceof FactoryBean)) { throw new BeanCreationException(beanName, "Bean instance of type [" + beanInstance.getClass() + "] is not a FactoryBean"); } return (FactoryBean) beanInstance; } //移除單例類這個方法重寫,父類的移除以外,還要移除factoryBeanObjectCache中的。 @Override protected void removeSingleton(String beanName) { super.removeSingleton(beanName); this.factoryBeanObjectCache.remove(beanName); } //返回當前容器的安全訪問上下文 protected AccessControlContext getAccessControlContext() { return AccessController.getContext(); } }
具體:express
一、1個不可變的實例屬性ConcurrentHashMap來存放工廠Bean生產的單例的集合:FactoryBean name --> object。apache
二、1個方法返回指定FactoryBean的類型的方法。數組
三、1個根據FactoryBean名,返回其生產的Object的方法。緩存
四、2個從工廠Bean中取實例的方法。實際是一個方法調用另外一個,取不到則返回空。安全
五、1個postProcessObjectFromFactoryBean的方法,留給子類重寫。app
六、1個取工廠Bean的方法——若是這個Object是FactoryBean類型,就轉換成FactoryBean返回less
七、1個重寫父類的removeSingleton方法,移除單例的時候,父類的移除以外,還要移除factoryBeanObjectCache中的。
八、1個返回當前容器的安全訪問上下文的方法。
總結:
這個類FactoryBeanRegistrySupport,類如其名,實現了對工廠Bean註冊的支持。值得注意的是,這個類有較多相似以下的寫法:
if (System.getSecurityManager() != null) {//若是當前系統存在安全管理器 return AccessController.doPrivileged(new PrivilegedAction<Class>() { public Class run() { //實際處理 } }, getAccessControlContext()); } else {//不存在安全管理器,就直接調用! //實際處理 }
這個方法的意思是,若是當前系統存在安全管理器,那麼接下來的操做不作權限檢查,直接調用。而若是不存在,OK,那固然是直接調用了。這是JDK層面的一個系統安全管理工具,某些狀況下,能夠避免系統進行安全檢查。這裏稍做了解便可。在學習JVM的時候可仔細瞭解原理。
除此以外,這裏能夠了解一下這個類比較重要的方法doGetObjectFromFactoryBean,是從工廠Bean中取實例的方法,源碼已經給出,這裏重點指出一下,沒必要摺疊了:
//從工廠Bean中取實例,shouldPostProcess指的是是否容許提早處理 private Object doGetObjectFromFactoryBean( final FactoryBean factory, final String beanName, final boolean shouldPostProcess) throws BeanCreationException { Object object; //跟getTypeForFactoryBean的實現同樣。 try { if (System.getSecurityManager() != null) {//若系統存在安全管理器 AccessControlContext acc = getAccessControlContext();//獲得當前容器的安全訪問上下文 try {//返回factoryBean的類型這個操做不作權限檢查,直接調用 object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { return factory.getObject(); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else {//不然直接取 object = factory.getObject(); } } catch (FactoryBeanNotInitializedException ex) { throw new BeanCurrentlyInCreationException(beanName, ex.toString()); } catch (Throwable ex) { throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex); } //若是從beanFactory取不到,且這個實例即將被建立,拋出異常 if (object == null && isSingletonCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException( beanName, "FactoryBean which is currently in creation returned null from getObject"); } //若取不到,並不是即將建立、且這個實例容許前處理 if (object != null && shouldPostProcess) { try { object = postProcessObjectFromFactoryBean(object, beanName);//這裏簡單返回,前處理的功能留給子類重寫 } catch (Throwable ex) { throw new BeanCreationException(beanName, "Post-processing of the FactoryBean's object failed", ex); } } return object; }
相信上面已經解釋的很清楚了。
2、最重要的抽象類——AbstractBeanFactory
(PS:這個類的方法實在是多的駭人,看得我實在是頭都大了。很少看到後面,發現不少方法其實也就是那麼回事。源碼註釋了大部分,且看看咯!)
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory { //父工廠的引用 private BeanFactory parentBeanFactory; //類加載器 private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); //臨時類加載器 private ClassLoader tempClassLoader; /** Whether to cache bean metadata or rather reobtain it for every access */ private boolean cacheBeanMetadata = true; //Bean表達式分解器,用來分解Bean定義中的表達式 private BeanExpressionResolver beanExpressionResolver; //轉換服務,用來替代屬性編輯器的 private ConversionService conversionService; //屬性編輯登記員集合,容量爲4的LinkedHashSet private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet<PropertyEditorRegistrar>(4); //通用的類型轉換器,重寫了默認的屬相編輯器機制 private TypeConverter typeConverter; //默認的屬性編輯器集合 private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<Class<?>, Class<? extends PropertyEditor>>(4); //嵌入值轉換器集合 private final List<StringValueResolver> embeddedValueResolvers = new LinkedList<StringValueResolver>(); //BeanPostProcessor處理器集合 private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>(); //標記是否有InstantiationAwareBeanPostProcessors實例被註冊 private boolean hasInstantiationAwareBeanPostProcessors; //標記是否有DestructionAwareBeanPostProcessors實例被註冊 private boolean hasDestructionAwareBeanPostProcessors; //範圍標識符和Scope實例的對應的Map private final Map<String, Scope> scopes = new HashMap<String, Scope>(8); //安全上下文Provider,能夠獲得安全管理器的安全上下文 private SecurityContextProvider securityContextProvider; //合併後的Bean根定義的集合 private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<String, RootBeanDefinition>(64); //至少被建立過一次的Bean的集合 private final Map<String, Boolean> alreadyCreated = new ConcurrentHashMap<String, Boolean>(64); //當前正在建立的原型,當前線程相關 private final ThreadLocal<Object> prototypesCurrentlyInCreation = new NamedThreadLocal<Object>("Prototype beans currently in creation"); //空構造方法 public AbstractBeanFactory() { } //指定父Bean工廠的構造方法 public AbstractBeanFactory(BeanFactory parentBeanFactory) { this.parentBeanFactory = parentBeanFactory; } //--------------------------------------------------------------------- // 3個getBean,BeanFactory接口的實現方法,實質是在調用doGetBean //--------------------------------------------------------------------- public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); } public <T> T getBean(String name, Class<T> requiredType) throws BeansException { return doGetBean(name, requiredType, null, false); } public Object getBean(String name, Object... args) throws BeansException { return doGetBean(name, null, args, false); } // 提供建立時須要參數列表的getBean public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException { return doGetBean(name, requiredType, args, false); } //從容器中獲取bean的基本方法。 @SuppressWarnings("unchecked") protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name);//在aliasMap中取得的標準名 Object bean; // Eagerly check singleton cache for manually registered singletons. Object sharedInstance = getSingleton(beanName);//首先在單例集合中取 if (sharedInstance != null && args == null) {//若是取獲得,沒有指定參數 if (logger.isDebugEnabled()) {//若Log容許調試 if (isSingletonCurrentlyInCreation(beanName)) {//若正準備建立,輸出日誌 logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); } } ////根據給定的實例是否爲工廠Bean,返回它本身或工廠Bean建立的實例 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { if (isPrototypeCurrentlyInCreation(beanName)) {//若是正在被建立,就拋出異常 throw new BeanCurrentlyInCreationException(beanName); } BeanFactory parentBeanFactory = getParentBeanFactory();//取本容器的父容器 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {//若存在父容器,且本容器不存在對應的Bean定義 String nameToLookup = originalBeanName(name);//取原始的Bean名 if (args != null) {//若參數列表存在 // 那麼用父容器根據原始Bean名和參數列表返回 return (T) parentBeanFactory.getBean(nameToLookup, args); } else { // 參數列表不要求,那就直接根據原始名稱和要求的類型返回 return parentBeanFactory.getBean(nameToLookup, requiredType); } } //若是不須要類型檢查,標記其已經被建立 if (!typeCheckOnly) { markBeanAsCreated(beanName); } //根據beanName取其根Bean定義 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); String[] dependsOn = mbd.getDependsOn();//獲得這個根定義的全部依賴 if (dependsOn != null) { for (String dependsOnBean : dependsOn) { getBean(dependsOnBean);//註冊這個Bean //註冊一個Bean和依賴於它的Bean(後參數依賴前參數) registerDependentBean(dependsOnBean, beanName); } } // 若是Bean定義是單例,就在返回單例 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { public Object getObject() throws BeansException { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { destroySingleton(beanName); throw ex; } } }); //根據給定的實例是否爲工廠Bean,返回它本身或工廠Bean建立的實例 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } //若是是原型 else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName);//原型建立前,與當前線程綁定 prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName);//原型建立後,與當前線程解除綁定 } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else {//既不是單例又不是原型的狀況 String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName);//獲得範圍 if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'"); } try {//根據範圍建立實例 Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() { public Object getObject() throws BeansException { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args);//原型建立前,與當前線程綁定 } finally { ////原型建立後,與當前線程解除綁定 afterPrototypeCreation(beanName); } } }); //根據給定的實例是否爲工廠Bean,返回它本身或工廠Bean建立的實例 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; " + "consider defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } } } //判斷要求的類型是否和Bean實例的類型正在匹配 if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { try { return getTypeConverter().convertIfNecessary(bean, requiredType);//轉換類型,不拋出異常就說明類型匹配 } catch (TypeMismatchException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to convert bean '" + name + "' to required type [" + ClassUtils.getQualifiedName(requiredType) + "]", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; } //判斷本容器是否包含指定bean public boolean containsBean(String name) { String beanName = transformedBeanName(name); // (若是是否包含單例 或 包含Bean定義)且 (爲工廠Bean的產物 或 自己就是工廠bean),就返回true if (containsSingleton(beanName) || containsBeanDefinition(beanName)) { return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name)); } // 若是不包含單例且不包含Bean定義,就從父類去查找 BeanFactory parentBeanFactory = getParentBeanFactory(); return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name))); } //判斷指定Bean是否爲單例 public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); Object beanInstance = getSingleton(beanName, false);//首先從單例集合中取 if (beanInstance != null) {//取不到,就判斷它是否是FactoryBean的實例 if (beanInstance instanceof FactoryBean) { // 若是是,要求它是工廠Bean產生的實例或這個工廠bean是單例 return (BeanFactoryUtils.isFactoryDereference(name) || ((FactoryBean<?>) beanInstance).isSingleton()); } else {// 若是不是,要求它不是工廠Bean產生的實例 return !BeanFactoryUtils.isFactoryDereference(name); } }//若雖然取不到,可是單例集合中包含它的名字,說明它是單例 else if (containsSingleton(beanName)) { return true; } else { //從父工廠中去查詢Bean定義 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { //父工廠找不到Bean定義,那就在父工廠根據原始名去查是否爲單例 return parentBeanFactory.isSingleton(originalBeanName(name)); } //返回一個合併後的根Bean定義 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // In case of FactoryBean, return singleton status of created object if not a dereference. //若該根定義是單例 if (mbd.isSingleton()) { if (isFactoryBean(beanName, mbd)) { //若該根定義爲工廠Bean if (BeanFactoryUtils.isFactoryDereference(name)) {//判斷是否爲工廠產生的實例 return true; } //取對應的工廠,判斷該工廠Bean是否爲單例 FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); return factoryBean.isSingleton(); } else { // 是否不爲工廠Bean產生的實例(此時,即,該根定義不爲工廠Bean,且不爲工廠Bean產生的實例的時候,因爲根定義是單例,那麼它就是單例) return !BeanFactoryUtils.isFactoryDereference(name); } } else { return false; } } } //判斷是否爲原型 public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); BeanFactory parentBeanFactory = getParentBeanFactory();//獲得父工廠 //若父工廠中的定義爲原型,就爲原型 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { return parentBeanFactory.isPrototype(originalBeanName(name)); } //若合併後的根定義爲原型,且不是工廠Bean產生的實例、或自己是工廠Bean,那麼就爲原型 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); if (mbd.isPrototype()) { return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd)); } else { if (BeanFactoryUtils.isFactoryDereference(name)) {//若爲工廠Bean產生的實例 return false; } if (isFactoryBean(beanName, mbd)) {//若爲工廠Bean,取它產生的Bean,判斷SmartFactoryBean final FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); if (System.getSecurityManager() != null) { return AccessController.doPrivileged(new PrivilegedAction<Boolean>() { public Boolean run() { return ((factoryBean instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factoryBean).isPrototype()) || !factoryBean.isSingleton()); } }, getAccessControlContext()); } else { return ((factoryBean instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factoryBean).isPrototype()) || !factoryBean.isSingleton()); } } else { return false; } } } //判斷類型是否匹配 public boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); Class<?> typeToMatch = (targetType != null ? targetType : Object.class); Object beanInstance = getSingleton(beanName, false);//取name對應的單例 if (beanInstance != null) { if (beanInstance instanceof FactoryBean) {//若爲工廠Bean //若不是工廠Bean產生的實例 if (!BeanFactoryUtils.isFactoryDereference(name)) { //取工廠Bean的類型與targetType進行對比 Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance); return (type != null && ClassUtils.isAssignable(typeToMatch, type)); } else { return ClassUtils.isAssignableValue(typeToMatch, beanInstance); } } //不是工廠Bean,那就直接判斷 else { return !BeanFactoryUtils.isFactoryDereference(name) && ClassUtils.isAssignableValue(typeToMatch, beanInstance); } } //單例表中,對應的Key沒有值,也不包含Bean定義,說明沒有註冊,返回false else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) { return false; } //如下是包含Bean定義的狀況 else { //先查父類的Bean定義 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.isTypeMatch(originalBeanName(name), targetType); } //直接查合併後的根定義 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); //構建類型數組 Class[] typesToMatch = (FactoryBean.class.equals(typeToMatch) ? new Class[] {typeToMatch} : new Class[] {FactoryBean.class, typeToMatch}); // Check decorated bean definition, if any: We assume it'll be easier // to determine the decorated bean's type than the proxy's type. //獲得Bean定義的持有者 BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {//若爲Bean工廠生成的實例,先獲得根定義 RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd); Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);//獲得預測的根定義 if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return typeToMatch.isAssignableFrom(targetClass); } } Class<?> beanType = predictBeanType(beanName, mbd, typesToMatch);//預測後的類型 if (beanType == null) { return false; } if (FactoryBean.class.isAssignableFrom(beanType)) {//BeanFactory是否爲其子類 if (!BeanFactoryUtils.isFactoryDereference(name)) {//若不爲工廠Bean的產物 // If it's a FactoryBean, we want to look at what it creates, not the factory class. beanType = getTypeForFactoryBean(beanName, mbd); if (beanType == null) { return false; } } } else if (BeanFactoryUtils.isFactoryDereference(name)) {//若爲工廠類Bean的產物 beanType = predictBeanType(beanName, mbd, FactoryBean.class);//預測類型 if (beanType == null || !FactoryBean.class.isAssignableFrom(beanType)) { return false; } } return typeToMatch.isAssignableFrom(beanType); } } //返回類型 public Class<?> getType(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); // Check manually registered singletons. Object beanInstance = getSingleton(beanName, false); if (beanInstance != null) { if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { return getTypeForFactoryBean((FactoryBean<?>) beanInstance); } else { return beanInstance.getClass(); } } else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) { // null instance registered return null; } else { // No singleton instance found -> check bean definition. BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.getType(originalBeanName(name)); } RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // Check decorated bean definition, if any: We assume it'll be easier // to determine the decorated bean's type than the proxy's type. BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) { RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd); Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd); if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return targetClass; } } Class<?> beanClass = predictBeanType(beanName, mbd); // Check bean class whether we're dealing with a FactoryBean. if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) { if (!BeanFactoryUtils.isFactoryDereference(name)) { // If it's a FactoryBean, we want to look at what it creates, not at the factory class. return getTypeForFactoryBean(beanName, mbd); } else { return beanClass; } } else { return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null); } } } //重寫了,獲得別名的方法。 @Override public String[] getAliases(String name) { String beanName = transformedBeanName(name); List<String> aliases = new ArrayList<String>(); boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX); String fullBeanName = beanName; if (factoryPrefix) { fullBeanName = FACTORY_BEAN_PREFIX + beanName; } if (!fullBeanName.equals(name)) { aliases.add(fullBeanName); } String[] retrievedAliases = super.getAliases(beanName); for (String retrievedAlias : retrievedAliases) { String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") + retrievedAlias; if (!alias.equals(name)) { aliases.add(alias); } } if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) { BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null) { aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName))); } } return StringUtils.toStringArray(aliases); } //--------------------------------------------------------------------- // Implementation of HierarchicalBeanFactory interface //--------------------------------------------------------------------- //返回本Bean工廠的父Bean工廠 public BeanFactory getParentBeanFactory() { return this.parentBeanFactory; } //是否在本容器中(就是說,並非工廠bean生產出來的) public boolean containsLocalBean(String name) { String beanName = transformedBeanName(name); // 轉換後的名字 //(是否爲單例或有對應的Bean定義) 且(不是工廠Bean生產出來的 或 自己就是工廠bean) return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) && (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName))); } //--------------------------------------------------------------------- // Implementation of ConfigurableBeanFactory interface //--------------------------------------------------------------------- public void setParentBeanFactory(BeanFactory parentBeanFactory) { if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) { throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory); } this.parentBeanFactory = parentBeanFactory; } public void setBeanClassLoader(ClassLoader beanClassLoader) { this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader()); } public ClassLoader getBeanClassLoader() { return this.beanClassLoader; } public void setTempClassLoader(ClassLoader tempClassLoader) { this.tempClassLoader = tempClassLoader; } public ClassLoader getTempClassLoader() { return this.tempClassLoader; } public void setCacheBeanMetadata(boolean cacheBeanMetadata) { this.cacheBeanMetadata = cacheBeanMetadata; } public boolean isCacheBeanMetadata() { return this.cacheBeanMetadata; } public void setBeanExpressionResolver(BeanExpressionResolver resolver) { this.beanExpressionResolver = resolver; } public BeanExpressionResolver getBeanExpressionResolver() { return this.beanExpressionResolver; } public void setConversionService(ConversionService conversionService) { this.conversionService = conversionService; } public ConversionService getConversionService() { return this.conversionService; } public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) { Assert.notNull(registrar, "PropertyEditorRegistrar must not be null"); this.propertyEditorRegistrars.add(registrar); } /** * Return the set of PropertyEditorRegistrars. */ public Set<PropertyEditorRegistrar> getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } public void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass) { Assert.notNull(requiredType, "Required type must not be null"); Assert.isAssignable(PropertyEditor.class, propertyEditorClass); this.customEditors.put(requiredType, propertyEditorClass); } public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) { registerCustomEditors(registry); } /** * Return the map of custom editors, with Classes as keys and PropertyEditor classes as values. */ public Map<Class<?>, 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 {//若本容器未註冊類型轉換器,就建立一個簡單的類型轉換器 SimpleTypeConverter typeConverter = new SimpleTypeConverter(); typeConverter.setConversionService(getConversionService()); registerCustomEditors(typeConverter); return typeConverter; } } public void addEmbeddedValueResolver(StringValueResolver valueResolver) { Assert.notNull(valueResolver, "StringValueResolver must not be null"); this.embeddedValueResolvers.add(valueResolver); } public String resolveEmbeddedValue(String value) { String result = value; for (StringValueResolver resolver : this.embeddedValueResolvers) { if (result == null) { return null; } result = resolver.resolveStringValue(result); } return result; } public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) { Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null"); this.beanPostProcessors.remove(beanPostProcessor); this.beanPostProcessors.add(beanPostProcessor); if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) { this.hasInstantiationAwareBeanPostProcessors = true; } if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) { this.hasDestructionAwareBeanPostProcessors = true; } } public int getBeanPostProcessorCount() { return this.beanPostProcessors.size(); } /** * Return the list of BeanPostProcessors that will get applied * to beans created with this factory. */ public List<BeanPostProcessor> getBeanPostProcessors() { return this.beanPostProcessors; } /** * Return whether this factory holds a InstantiationAwareBeanPostProcessor * that will get applied to singleton beans on shutdown. * @see #addBeanPostProcessor * @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor */ protected boolean hasInstantiationAwareBeanPostProcessors() { return this.hasInstantiationAwareBeanPostProcessors; } /** * Return whether this factory holds a DestructionAwareBeanPostProcessor * that will get applied to singleton beans on shutdown. * @see #addBeanPostProcessor * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor */ protected boolean hasDestructionAwareBeanPostProcessors() { return this.hasDestructionAwareBeanPostProcessors; } public void registerScope(String scopeName, Scope scope) { Assert.notNull(scopeName, "Scope identifier must not be null"); Assert.notNull(scope, "Scope must not be null"); if (SCOPE_SINGLETON.equals(scopeName) || SCOPE_PROTOTYPE.equals(scopeName)) { throw new IllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'"); } this.scopes.put(scopeName, scope); } public String[] getRegisteredScopeNames() { return StringUtils.toStringArray(this.scopes.keySet()); } public Scope getRegisteredScope(String scopeName) { Assert.notNull(scopeName, "Scope identifier must not be null"); return this.scopes.get(scopeName); } /** * Set the security context provider for this bean factory. If a security manager * is set, interaction with the user code will be executed using the privileged * of the provided security context. */ public void setSecurityContextProvider(SecurityContextProvider securityProvider) { this.securityContextProvider = securityProvider; } /** * Delegate the creation of the access control context to the * {@link #setSecurityContextProvider SecurityContextProvider}. */ @Override public AccessControlContext getAccessControlContext() { return (this.securityContextProvider != null ? this.securityContextProvider.getAccessControlContext() : AccessController.getContext()); } public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { Assert.notNull(otherFactory, "BeanFactory must not be null"); setBeanClassLoader(otherFactory.getBeanClassLoader()); setCacheBeanMetadata(otherFactory.isCacheBeanMetadata()); setBeanExpressionResolver(otherFactory.getBeanExpressionResolver()); if (otherFactory instanceof AbstractBeanFactory) { AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory; this.customEditors.putAll(otherAbstractFactory.customEditors); this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars); this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors); this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors || otherAbstractFactory.hasInstantiationAwareBeanPostProcessors; this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors || otherAbstractFactory.hasDestructionAwareBeanPostProcessors; this.scopes.putAll(otherAbstractFactory.scopes); this.securityContextProvider = otherAbstractFactory.securityContextProvider; } else { setTypeConverter(otherFactory.getTypeConverter()); } } //返回合併後的bean定義(父Bean定義和子Bean定義合併) public BeanDefinition getMergedBeanDefinition(String name) throws BeansException { String beanName = transformedBeanName(name); // Efficiently check whether bean definition exists in this factory. //若Bean定義不存在,且本容器父工廠爲ConfigurableBeanFactory的實例,讓父工廠來調用這個方法 if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) { return ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(beanName); } //不然直接從本地合併後的Bean定義中取 return getMergedLocalBeanDefinition(beanName); } public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); Object beanInstance = getSingleton(beanName, false); if (beanInstance != null) { return (beanInstance instanceof FactoryBean); } else if (containsSingleton(beanName)) { // null instance registered return false; } // No singleton instance found -> check bean definition. if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) { // No bean definition found in this factory -> delegate to parent. return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name); } return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName)); } @Override public boolean isActuallyInCreation(String beanName) { return isSingletonCurrentlyInCreation(beanName) || isPrototypeCurrentlyInCreation(beanName); } // 判斷指定的原型是否正在被建立 protected boolean isPrototypeCurrentlyInCreation(String beanName) { Object curVal = this.prototypesCurrentlyInCreation.get(); return (curVal != null && (curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName)))); } //原型建立前回調,須要子類重寫 @SuppressWarnings("unchecked") protected void beforePrototypeCreation(String beanName) { Object curVal = this.prototypesCurrentlyInCreation.get(); if (curVal == null) {//原型建立狀態與當前線程綁定 this.prototypesCurrentlyInCreation.set(beanName); } else if (curVal instanceof String) { Set<String> beanNameSet = new HashSet<String>(2); beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } //這裏多餘了。。。 else { Set<String> beanNameSet = (Set<String>) curVal; beanNameSet.add(beanName); } } //建立原型後,從當前線程解除綁定 @SuppressWarnings("unchecked") protected void afterPrototypeCreation(String beanName) { Object curVal = this.prototypesCurrentlyInCreation.get(); if (curVal instanceof String) { this.prototypesCurrentlyInCreation.remove(); } else if (curVal instanceof Set) { Set<String> beanNameSet = (Set<String>) curVal; beanNameSet.remove(beanName); if (beanNameSet.isEmpty()) { this.prototypesCurrentlyInCreation.remove(); } } } public void destroyBean(String beanName, Object beanInstance) { destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName)); } /** * Destroy the given bean instance (usually a prototype instance * obtained from this factory) according to the given bean definition. * @param beanName the name of the bean definition * @param beanInstance the bean instance to destroy * @param mbd the merged bean definition */ protected void destroyBean(String beanName, Object beanInstance, RootBeanDefinition mbd) { new DisposableBeanAdapter(beanInstance, beanName, mbd, getBeanPostProcessors(), getAccessControlContext()).destroy(); } public void destroyScopedBean(String beanName) { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); if (mbd.isSingleton() || mbd.isPrototype()) { throw new IllegalArgumentException( "Bean name '" + beanName + "' does not correspond to an object in a mutable scope"); } String scopeName = mbd.getScope(); Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope SPI registered for scope '" + scopeName + "'"); } Object bean = scope.remove(beanName); if (bean != null) { destroyBean(beanName, bean, mbd); } } //--------------------------------------------------------------------- // Implementation methods //--------------------------------------------------------------------- //變換後的Bean名稱(先去掉BeanFactory前綴,而後在aliasMap中取標準名) protected String transformedBeanName(String name) { return canonicalName(BeanFactoryUtils.transformedBeanName(name)); } //返回原始的Bean名 protected String originalBeanName(String name) { String beanName = transformedBeanName(name); if (name.startsWith(FACTORY_BEAN_PREFIX)) { beanName = FACTORY_BEAN_PREFIX + beanName; } return beanName; } /** * Initialize the given BeanWrapper with the custom editors registered * with this factory. To be called for BeanWrappers that will create * and populate bean instances. * <p>The default implementation delegates to {@link #registerCustomEditors}. * Can be overridden in subclasses. * @param bw the BeanWrapper to initialize */ protected void initBeanWrapper(BeanWrapper bw) { bw.setConversionService(getConversionService()); registerCustomEditors(bw); } /** * Initialize the given PropertyEditorRegistry with the custom editors * that have been registered with this BeanFactory. * <p>To be called for BeanWrappers that will create and populate bean * instances, and for SimpleTypeConverter used for constructor argument * and factory method type conversion. * @param registry the PropertyEditorRegistry to initialize */ protected void registerCustomEditors(PropertyEditorRegistry registry) { PropertyEditorRegistrySupport registrySupport = (registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null); if (registrySupport != null) { registrySupport.useConfigValueEditors(); } if (!this.propertyEditorRegistrars.isEmpty()) { for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) { try { registrar.registerCustomEditors(registry); } catch (BeanCreationException ex) { Throwable rootCause = ex.getMostSpecificCause(); if (rootCause instanceof BeanCurrentlyInCreationException) { BeanCreationException bce = (BeanCreationException) rootCause; if (isCurrentlyInCreation(bce.getBeanName())) { if (logger.isDebugEnabled()) { logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() + "] failed because it tried to obtain currently created bean '" + ex.getBeanName() + "': " + ex.getMessage()); } onSuppressedException(ex); continue; } } throw ex; } } } if (!this.customEditors.isEmpty()) { for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : this.customEditors.entrySet()) { Class<?> requiredType = entry.getKey(); Class<? extends PropertyEditor> editorClass = entry.getValue(); registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass)); } } } //返回一個合併後的根Bean定義(父Bean定義和子Bean定義合併)(從當前容器取) protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException { // Quick check on the concurrent map first, with minimal locking. RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);//首先直接從合併根定義集合中取 if (mbd != null) { return mbd; } //根據bean名和其對應的Bean定義,取其根Bean根定義 return getMergedBeanDefinition(beanName, getBeanDefinition(beanName)); } //根據Bean名和Bean定義取其Bean根定義 protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd) throws BeanDefinitionStoreException { return getMergedBeanDefinition(beanName, bd, null);//調用重載方法 } //根據Bean名稱返回根定義(若給定的Bean定義爲子Bean定義,那麼合併它的父Bean定義) protected RootBeanDefinition getMergedBeanDefinition( String beanName, BeanDefinition bd, BeanDefinition containingBd) throws BeanDefinitionStoreException { synchronized (this.mergedBeanDefinitions) { RootBeanDefinition mbd = null; //若給定的Bean定義並無包含子Bean定義,那麼直接根據Bean名取根定義 if (containingBd == null) { mbd = this.mergedBeanDefinitions.get(beanName); } if (mbd == null) {//若取不到 if (bd.getParentName() == null) {//若Bean定義沒有父類,就很簡單了 if (bd instanceof RootBeanDefinition) {//若Bean定義是RootBeanDefinition的實例,克隆、強轉後返回 mbd = ((RootBeanDefinition) bd).cloneBeanDefinition(); } else {//不然,根據Bean定義,來構造一個根Bean定義 mbd = new RootBeanDefinition(bd); } } else {//若Bean定義有父類 // Child bean definition: needs to be merged with parent. BeanDefinition pbd; try { String parentBeanName = transformedBeanName(bd.getParentName());//取其父Bean定義的名字 if (!beanName.equals(parentBeanName)) {//若Bean名字並非bd的父Bean的名字 pbd = getMergedBeanDefinition(parentBeanName);//根據父Bean定義名稱來返回合併後的bean定義 } else {//若是beanName對應的Bean就是bd的父Bean if (getParentBeanFactory() instanceof ConfigurableBeanFactory) {//若父Bean工廠爲ConfigurableBeanFactory的實例 // 那麼強轉成ConfigurableBeanFactory後再調用合併方法 pbd = ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(parentBeanName); } else {//若父Bean工廠不是ConfigurableBeanFactory的實例,就拋出異常 throw new NoSuchBeanDefinitionException(bd.getParentName(), "Parent name '" + bd.getParentName() + "' is equal to bean name '" + beanName + "': cannot be resolved without an AbstractBeanFactory parent"); } } } catch (NoSuchBeanDefinitionException ex) { throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName, "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex); } // 深度複製 mbd = new RootBeanDefinition(pbd);//根據Bean定義生成一個根Bean定義 mbd.overrideFrom(bd);//將Bean定義的屬性複製進本身的定義(根Bean定義)中 } if (!StringUtils.hasLength(mbd.getScope())) {//若是根Bean定義未設置範圍 mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);//那麼設置其範圍爲單例 } // 若本根Bean定義包含Bean定義、本根Bean定義爲單例且包含的Bean定義並非單例 if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) { mbd.setScope(containingBd.getScope());// 那麼將本根Bean定義的範圍設置爲包含的Bean定義的範圍 } //若本根Bean定義不包含Bean定義,且是緩存Bean元數據(重寫前均爲true)且Bean定義是否有資格緩存(默認實現是,這個Bean已經建立便有資格) if (containingBd == null && isCacheBeanMetadata() && isBeanEligibleForMetadataCaching(beanName)) { this.mergedBeanDefinitions.put(beanName, mbd);//放進mergedBeanDefinitions中 } } return mbd; } } //檢查Bean定義,拋出異常 protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, Object[] args) throws BeanDefinitionStoreException { if (mbd.isAbstract()) { throw new BeanIsAbstractException(beanName); } if (args != null && !mbd.isPrototype()) { throw new BeanDefinitionStoreException( "Can only specify arguments for the getBean method when referring to a prototype bean definition"); } } /** * Remove the merged bean definition for the specified bean, * recreating it on next access. * @param beanName the bean name to clear the merged definition for */ protected void clearMergedBeanDefinition(String beanName) { this.mergedBeanDefinitions.remove(beanName); } //解析類型,處理異常 protected Class<?> resolveBeanClass(final RootBeanDefinition mbd, String beanName, final Class<?>... typesToMatch) throws CannotLoadBeanClassException { try { if (mbd.hasBeanClass()) { return mbd.getBeanClass(); } if (System.getSecurityManager() != null) { return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { public Class<?> run() throws Exception { return doResolveBeanClass(mbd, typesToMatch); } }, getAccessControlContext()); } else { return doResolveBeanClass(mbd, typesToMatch); } } catch (PrivilegedActionException pae) { ClassNotFoundException ex = (ClassNotFoundException) pae.getException(); throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex); } catch (ClassNotFoundException ex) { throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex); } catch (LinkageError err) { throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err); } } // 真正的解析類型 private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch) throws ClassNotFoundException { if (!ObjectUtils.isEmpty(typesToMatch)) { ClassLoader tempClassLoader = getTempClassLoader();//找到臨時的類加載器 if (tempClassLoader != null) { if (tempClassLoader instanceof DecoratingClassLoader) {//若爲裝飾類加載器 DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader; for (Class<?> typeToMatch : typesToMatch) { dcl.excludeClass(typeToMatch.getName()); } } String className = mbd.getBeanClassName(); return (className != null ? ClassUtils.forName(className, tempClassLoader) : null); } } return mbd.resolveBeanClass(getBeanClassLoader()); } /** * Evaluate the given String as contained in a bean definition, * potentially resolving it as an expression. * @param value the value to check * @param beanDefinition the bean definition that the value comes from * @return the resolved value * @see #setBeanExpressionResolver */ protected Object evaluateBeanDefinitionString(String value, BeanDefinition beanDefinition) { if (this.beanExpressionResolver == null) { return value; } Scope scope = (beanDefinition != null ? getRegisteredScope(beanDefinition.getScope()) : null); return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope)); } //預測類型 protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) { //若根Bena定義的工廠方法名存在,說明它是工廠Bean建立的,沒法預測類型? if (mbd.getFactoryMethodName() != null) { return null; } //不然,解析Bean的Class return resolveBeanClass(mbd, beanName, typesToMatch); } /** * Check whether the given bean is defined as a {@link FactoryBean}. * @param beanName the name of the bean * @param mbd the corresponding bean definition */ protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) { Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class); return (beanType != null && FactoryBean.class.isAssignableFrom(beanType)); } //返回工廠Bean的類型 protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) { if (!mbd.isSingleton()) { return null; } try { FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true); return getTypeForFactoryBean(factoryBean); } catch (BeanCreationException ex) { // Can only happen when getting a FactoryBean. if (logger.isDebugEnabled()) { logger.debug("Ignoring bean creation exception on FactoryBean type check: " + ex); } onSuppressedException(ex); return null; } } //標記這個Bean已經被建立 protected void markBeanAsCreated(String beanName) { this.alreadyCreated.put(beanName, Boolean.TRUE); } /** * Determine whether the specified bean is eligible for having * its bean definition metadata cached. * @param beanName the name of the bean * @return {@code true} if the bean's metadata may be cached * at this point already */ //若本根Bean定義包含Bean元定義做爲緩存,這個方法應被之類覆蓋,這裏僅判斷Bean是否已經被建立 protected boolean isBeanEligibleForMetadataCaching(String beanName) { return this.alreadyCreated.containsKey(beanName); } /** * Remove the singleton instance (if any) for the given bean name, * but only if it hasn't been used for other purposes than type checking. * @param beanName the name of the bean * @return {@code true} if actually removed, {@code false} otherwise */ protected boolean removeSingletonIfCreatedForTypeCheckOnly(String beanName) { if (!this.alreadyCreated.containsKey(beanName)) { removeSingleton(beanName); return true; } else { return false; } } //根據給定的實例是否爲工廠Bean,返回它本身或工廠Bean建立的實例 protected Object getObjectForBeanInstance( Object beanInstance, String name, String beanName, RootBeanDefinition mbd) { //若是這個Bean是工廠Bean建立的 且 這個Bean實例並非FactoryBean實例,拋異常 if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) { throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass()); } //若是這個Bean實例並非FactoryBean實例 或 這個Bean是工廠Bean建立的,直接返回 if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) { return beanInstance; } //——————————如下都是 這個Bean實例是FactoryBean實例的狀況 Object object = null; if (mbd == null) {//若根Bean定義爲空,取這個BeanFactory所生產的實例 object = getCachedObjectForFactoryBean(beanName); } if (object == null) {//若取不到,那麼手動取 FactoryBean<?> factory = (FactoryBean<?>) beanInstance;//把這個實例轉化成一個FactoryBean // Caches object obtained from FactoryBean if it is a singleton. if (mbd == null && containsBeanDefinition(beanName)) {//若根Bean定義爲空,可是容器內有Bean定義 mbd = getMergedLocalBeanDefinition(beanName);//返回合併後的Bean定義 } boolean synthetic = (mbd != null && mbd.isSynthetic());//標記這個Bean定義是合併的 object = getObjectFromFactoryBean(factory, beanName, !synthetic);//從工廠Bean中取 } return object; } //判斷給定的Bean是否被使用過 public boolean isBeanNameInUse(String beanName) { //如果別名 或 並不是工廠bean生產出來的 或 被其餘某個bean所依賴,那麼判斷其被使用過 return isAlias(beanName) || containsLocalBean(beanName) || hasDependentBean(beanName); } /** * Determine whether the given bean requires destruction on shutdown. * <p>The default implementation checks the DisposableBean interface as well as * a specified destroy method and registered DestructionAwareBeanPostProcessors. * @param bean the bean instance to check * @param mbd the corresponding bean definition * @see org.springframework.beans.factory.DisposableBean * @see AbstractBeanDefinition#getDestroyMethodName() * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor */ protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) { return (bean != null && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || hasDestructionAwareBeanPostProcessors())); } /** * Add the given bean to the list of disposable beans in this factory, * registering its DisposableBean interface and/or the given destroy method * to be called on factory shutdown (if applicable). Only applies to singletons. * @param beanName the name of the bean * @param bean the bean instance * @param mbd the bean definition for the bean * @see RootBeanDefinition#isSingleton * @see RootBeanDefinition#getDependsOn * @see #registerDisposableBean * @see #registerDependentBean */ protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) { AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null); if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) { if (mbd.isSingleton()) { // Register a DisposableBean implementation that performs all destruction // work for the given bean: DestructionAwareBeanPostProcessors, // DisposableBean interface, custom destroy method. registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } else { // A bean with a custom scope... Scope scope = this.scopes.get(mbd.getScope()); if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + mbd.getScope() + "'"); } scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } } } //--------------------------------------------------------------------- // Abstract methods to be implemented by subclasses //--------------------------------------------------------------------- //標記是否包含Bean定義的方法 protected abstract boolean containsBeanDefinition(String beanName); //根據Bean名返回其BeanDefinition protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException; //根據指定的bean定義和bean名、參數,建立對象 protected abstract Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException; }
總結:方法太多了,一個個介紹很浪費時間,不具體介紹。大致介紹一下吧。這個AbstractBeanFactory繼承了支持工廠Bean註冊的FactoryBeanRegistrySupport,而且實現了BeanFactory重要的第三級接口——ConfigurableBeanFactory。須要具體瞭解這個接口,能夠去看我以前的接口分析——Spring源碼分析——BeanFactory體系之接口詳細分析 。ConfigurableBeanFactory是一個很是複雜的接口,繼承了HierarchicalBeanFactory和SingletonBeanRegistry,主要實現了工廠建立、註冊Bean、單例類註冊等各類功能。
AbstractBeanFactory實現了ConfigurableBeanFactory接口的絕大多數方法,實現了Bean工廠的許多重要功能,如BeanDefinition、RootBeanDefinition、原型、單例相關的各類操做。
下面列出一些主要方法實現,其餘的方法說明,可具體參照上文我貼出的大部分註釋過的源碼。
(1)、從容器中獲取bean的方法——doGetBean:
@SuppressWarnings("unchecked") protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name);//在aliasMap中取得的標準名 Object bean; // Eagerly check singleton cache for manually registered singletons. Object sharedInstance = getSingleton(beanName);//首先在單例集合中取 if (sharedInstance != null && args == null) {//若是取獲得,沒有指定參數 if (logger.isDebugEnabled()) {//若Log容許調試 if (isSingletonCurrentlyInCreation(beanName)) {//若正準備建立,輸出日誌 logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); } } ////根據給定的實例是否爲工廠Bean,返回它本身或工廠Bean建立的實例 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { if (isPrototypeCurrentlyInCreation(beanName)) {//若是正在被建立,就拋出異常 throw new BeanCurrentlyInCreationException(beanName); } BeanFactory parentBeanFactory = getParentBeanFactory();//取本容器的父容器 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {//若存在父容器,且本容器不存在對應的Bean定義 String nameToLookup = originalBeanName(name);//取原始的Bean名 if (args != null) {//若參數列表存在 // 那麼用父容器根據原始Bean名和參數列表返回 return (T) parentBeanFactory.getBean(nameToLookup, args); } else { // 參數列表不要求,那就直接根據原始名稱和要求的類型返回 return parentBeanFactory.getBean(nameToLookup, requiredType); } } //若是不須要類型檢查,標記其已經被建立 if (!typeCheckOnly) { markBeanAsCreated(beanName); } //根據beanName取其根Bean定義 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); String[] dependsOn = mbd.getDependsOn();//獲得這個根定義的全部依賴 if (dependsOn != null) { for (String dependsOnBean : dependsOn) { getBean(dependsOnBean);//註冊這個Bean //註冊一個Bean和依賴於它的Bean(後參數依賴前參數) registerDependentBean(dependsOnBean, beanName); } } // 若是Bean定義是單例,就在返回單例 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { public Object getObject() throws BeansException { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { destroySingleton(beanName); throw ex; } } }); //根據給定的實例是否爲工廠Bean,返回它本身或工廠Bean建立的實例 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } //若是是原型 else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName);//原型建立前,與當前線程綁定 prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName);//原型建立後,與當前線程解除綁定 } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else {//既不是單例又不是原型的狀況 String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName);//獲得範圍 if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'"); } try {//根據範圍建立實例 Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() { public Object getObject() throws BeansException { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args);//原型建立前,與當前線程綁定 } finally { ////原型建立後,與當前線程解除綁定 afterPrototypeCreation(beanName); } } }); //根據給定的實例是否爲工廠Bean,返回它本身或工廠Bean建立的實例 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; " + "consider defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } } } //判斷要求的類型是否和Bean實例的類型正在匹配 if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { try { return getTypeConverter().convertIfNecessary(bean, requiredType);//轉換類型,不拋出異常就說明類型匹配 } catch (TypeMismatchException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to convert bean '" + name + "' to required type [" + ClassUtils.getQualifiedName(requiredType) + "]", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; }
下面對這個方法進行簡要的解釋:
<1>、這個方法形參爲final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly,分別表示Bean的名稱、要求返回的Bean的類型、取Bean時提供的參數數組 以及 是否須要類型檢查。哦
<2>、final String beanName = transformedBeanName(name); 這個方法是從aliasMap中取得對應的標準名。方法實現是,首先去掉name的 FACTORY_BEAN_PREFIX 前綴(若是是工廠Bean自己,那麼Bean名有這個前綴),而後調用SimpleAliasRegistry的canonicalName方法。上篇博客已經介紹過SimpleAliasRegistry了,這裏貼一下這個方法的源碼:
/* * 根據name這個Key,在aliasMap中不斷循環的取對應的value,若是取獲得,就繼續根據這個value取值,不斷循環繼續。 * 直到取不到,就把這個在aliasMap中無對應值的key返回。這個動做,叫規範名 */ public String canonicalName(String name) { String canonicalName = name; //規範名 // Handle aliasing... String resolvedName;//已解析名 do { resolvedName = this.aliasMap.get(canonicalName);//aliasMap中規範名對應的值賦值給已解析名 if (resolvedName != null) {//若是已解析名存在(即規範名在aliasMap中有對應的值) canonicalName = resolvedName; // 這個已解析名賦值給標準名 } } while (resolvedName != null);//不斷循環,直到已解析名不存在 return canonicalName; }
<3>、首先根據標準名beanName,在單例緩存中取對應的Bean:Object sharedInstance = getSingleton(beanName);
<4>、若是取獲得,且args爲空,根據給定的實例是否爲工廠Bean,返回它本身或工廠Bean建立的實例:bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);而後結束整個方法。這個方法源碼以下:
//根據給定的實例是否爲工廠Bean,返回它本身或工廠Bean建立的實例 protected Object getObjectForBeanInstance( Object beanInstance, String name, String beanName, RootBeanDefinition mbd) { //若是這個Bean是工廠Bean建立的 且 這個Bean實例並非FactoryBean實例,拋異常 if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) { throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass()); } //若是這個Bean實例並非FactoryBean實例 或 這個Bean是工廠Bean建立的,直接返回 if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) { return beanInstance; } //——————————如下都是 這個Bean實例是FactoryBean實例的狀況 Object object = null; if (mbd == null) {//若根Bean定義爲空,取這個BeanFactory所生產的實例 object = getCachedObjectForFactoryBean(beanName); } if (object == null) {//若取不到,那麼手動取 FactoryBean<?> factory = (FactoryBean<?>) beanInstance;//把這個實例轉化成一個FactoryBean // Caches object obtained from FactoryBean if it is a singleton. if (mbd == null && containsBeanDefinition(beanName)) {//若根Bean定義爲空,可是容器內有Bean定義 mbd = getMergedLocalBeanDefinition(beanName);//返回合併後的Bean定義 } boolean synthetic = (mbd != null && mbd.isSynthetic());//標記這個Bean定義是合併的 object = getObjectFromFactoryBean(factory, beanName, !synthetic);//從工廠Bean中取 } return object;
<5>、若是取不到、或 args 不爲空(下面都是基於這個條件):
(若是對應的Bean正在被建立,就拋出異常)首先用父容器(若是本容器有的話)根據給出的形參取對應的Bean。
<6>、此時,判斷,若是不須要類型檢查,標記其已經被建立。
<7>、根據beanName取本地合併後的RootBeanDefinition(這個方法getMergedLocalBeanDefinition涉及到多層BeanDefinition相關的調用),而後檢查一下。而後根據這個RootBeanDefinition,註冊這個Bean和它的全部依賴。
<8>、若是這個RootBeanDefinition是單例,先根據beanName從單例緩存中取,取不到就建立一個匿名內部Bean工廠,建立一個單例,直接結束方法。
<9>、若是這個RootBeanDefinition是原型,就直接建立一個Bean返回,並在建立前把beanName與當前線程綁定,建立後解綁。
<10>、若是這個RootBeanDefinition既不是單例,又不是原型,那麼根據這個RootBeanDefinition定義的範圍Scope,直接建立一個scopedInstance。
<11>、若這個scopedInstance爲工廠Bean,就獲得它建立的實例,不然獲得它自身。
<12>、對<9>或<11>中最後產生的Bean就進行一次檢查,要求這個產生的Bean的類型是否和Bean實例的類型匹配,不匹配就拋出異常。
以上就是這個doGetBean方法了。其餘的方法分析可參照上文的源碼。