zoukankan      html  css  js  c++  java
  • Spring 学习记录6 BeanFactory(2)

    主题

    除了Spring 学习记录5 BeanFactory 里写的几个接口外,BeanFactory的实现类还实现了一些其他接口,这篇文章主要介绍这些接口和实现类.

    结构

    DefaultListableBeanFactory和它的父类们除了实现了BF的各种接口以外还实现了AliasRegistry和BeanDefinitionRegistry接口.而且不同等级的父类和BF的相关接口都有交集..

    AliasRegistry

    这个接口根据说明来看意思是提供别名注册的服务.虽然没有实际使用过别名,不过1个bean确实可以有N个别名.

     1 /*
     2  * Copyright 2002-2008 the original author or authors.
     3  *
     4  * Licensed under the Apache License, Version 2.0 (the "License");
     5  * you may not use this file except in compliance with the License.
     6  * You may obtain a copy of the License at
     7  *
     8  *      http://www.apache.org/licenses/LICENSE-2.0
     9  *
    10  * Unless required by applicable law or agreed to in writing, software
    11  * distributed under the License is distributed on an "AS IS" BASIS,
    12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  * See the License for the specific language governing permissions and
    14  * limitations under the License.
    15  */
    16 
    17 package org.springframework.core;
    18 
    19 /**
    20  * Common interface for managing aliases. Serves as super-interface for
    21  * {@link org.springframework.beans.factory.support.BeanDefinitionRegistry}.
    22  *
    23  * @author Juergen Hoeller
    24  * @since 2.5.2
    25  */
    26 public interface AliasRegistry {
    27 
    28     /**
    29      * Given a name, register an alias for it.
    30      * @param name the canonical name
    31      * @param alias the alias to be registered
    32      * @throws IllegalStateException if the alias is already in use
    33      * and may not be overridden
    34      */
    35     void registerAlias(String name, String alias);
    36 
    37     /**
    38      * Remove the specified alias from this registry.
    39      * @param alias the alias to remove
    40      * @throws IllegalStateException if no such alias was found
    41      */
    42     void removeAlias(String alias);
    43 
    44     /**
    45      * Determine whether this given name is defines as an alias
    46      * (as opposed to the name of an actually registered component).
    47      * @param beanName the bean name to check
    48      * @return whether the given name is an alias
    49      */
    50     boolean isAlias(String beanName);
    51 
    52     /**
    53      * Return the aliases for the given name, if defined.
    54      * @param name the name to check for aliases
    55      * @return the aliases, or an empty array if none
    56      */
    57     String[] getAliases(String name);
    58 
    59 }
    View Code

    接口就4个方法.

    1.为1个beanname注册1个别名,

    2.删除1个别名

    3.判断1个name是否是别名

    4.根据beanname获取所有别名.

    SimpleAliasRegistry

    这个类实现了AliasRegistry,用了1个ConcurrentHashMap来存储所有别名的映射关系.

    测试代码:

     1 package spring.bf;
     2 
     3 import org.junit.Test;
     4 import org.junit.runner.RunWith;
     5 import org.springframework.core.SimpleAliasRegistry;
     6 import org.springframework.test.context.ContextConfiguration;
     7 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
     8 import org.springframework.util.StringValueResolver;
     9 
    10 import java.util.Arrays;
    11 
    12 @RunWith(SpringJUnit4ClassRunner.class)
    13 @ContextConfiguration("classpath:test-application-context.xml")
    14 public class SimpleAliasRegistryTest {
    15 
    16     SimpleAliasRegistry simpleAliasRegistry = new SimpleAliasRegistry();
    17 
    18     /**
    19      * 别名不能循环引用
    20      * 会调用checkForAliasCircle方法,做循环引用的检查
    21      * 里面会调用canonicalName方法,这个方法会不停的用传入的name当做别名去找他对应的beanname,层层找下去,找到最后1个beanname以后和alias比较一下,如果一直,说明有循环引用就抛出异常
    22      */
    23     @Test
    24     public void test() {
    25         simpleAliasRegistry.registerAlias("b1", "a1");
    26         simpleAliasRegistry.registerAlias("a1", "a2");
    27         //simpleAliasRegistry.registerAlias("a2", "b1"); //java.lang.IllegalStateException: Cannot register alias 'b1' for name 'a2': Circular reference - 'a2' is a direct or indirect alias for 'b1' already
    28     }
    29 
    30     /**
    31      * 默认情况下别名可以覆盖
    32      * 根据子类会不会重写allowAliasOverriding来做决定,默认是true
    33      */
    34     @Test
    35     public void test2() {
    36         simpleAliasRegistry.registerAlias("b1", "a1");
    37         simpleAliasRegistry.registerAlias("b2", "a1");
    38         System.out.println(Arrays.toString(simpleAliasRegistry.getAliases("b1"))); // []
    39         System.out.println(Arrays.toString(simpleAliasRegistry.getAliases("b2"))); // [a1]
    40     }
    41 
    42     /**
    43      * 移除不存在的bean会抛异常
    44      * 所以调用之前可以先用isAlias做判断
    45      */
    46     @Test
    47     public void test3() {
    48         //simpleAliasRegistry.removeAlias("not exists"); // java.lang.IllegalStateException: No alias 'not exists' registered
    49     }
    50 
    51     // getAliases会调用retrieveAliases方法,它会递归调用自身,根据beanname找到alias,再把alias当做beanname,把所有的alias都找出来.
    52 
    53     /**
    54      * 测试resolveAliases方法
    55      */
    56     @Test
    57     public void test4() {
    58         simpleAliasRegistry.registerAlias("b1", "a1");
    59         simpleAliasRegistry.registerAlias("b2", "a2");
    60         // 报错
    61         // java.lang.IllegalStateException: Cannot register resolved alias 'a1' (original: 'a2') for name 'b2': It is already registered for name 'b2'.
    62         // 提示感觉有问题.其实应该提示It is already registered for name 'b1'.
    63         // 因为alias a2 被解析为a1, 而a1已经指向的是beanname b1,所以不能再指向b2
    64         simpleAliasRegistry.resolveAliases(new StringValueResolver() {
    65             @Override
    66             public String resolveStringValue(String strVal) {
    67                 if (strVal.equals("a2")) {
    68                     return "a1";
    69                 }
    70                 return strVal;
    71             }
    72         });
    73     }
    74 }

    方法基本在测试里都测了.

    另外感觉resolveAliases有一个提示有点问题,请参test4方法.

    DefaultSingletonBeanRegistry

    直接上注释吧...很多方法目前还不知道为什么这么写.什么时候会用到.看到后面的子类可能就会懂了.

      1 /*
      2  * Copyright 2002-2015 the original author or authors.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package org.springframework.beans.factory.support;
     18 
     19 import org.apache.commons.logging.Log;
     20 import org.apache.commons.logging.LogFactory;
     21 import org.springframework.beans.factory.*;
     22 import org.springframework.beans.factory.config.SingletonBeanRegistry;
     23 import org.springframework.core.SimpleAliasRegistry;
     24 import org.springframework.util.Assert;
     25 import org.springframework.util.StringUtils;
     26 
     27 import java.util.*;
     28 import java.util.concurrent.ConcurrentHashMap;
     29 
     30 /**
     31  * Generic registry for shared bean instances, implementing the
     32  * {@link org.springframework.beans.factory.config.SingletonBeanRegistry}.
     33  * Allows for registering singleton instances that should be shared
     34  * for all callers of the registry, to be obtained via bean name.
     35  * <p>
     36  * <p>Also supports registration of
     37  * {@link org.springframework.beans.factory.DisposableBean} instances,
     38  * (which might or might not correspond to registered singletons),
     39  * to be destroyed on shutdown of the registry. Dependencies between
     40  * beans can be registered to enforce an appropriate shutdown order.
     41  * <p>
     42  * <p>This class mainly serves as base class for
     43  * {@link org.springframework.beans.factory.BeanFactory} implementations,
     44  * factoring out the common management of singleton bean instances. Note that
     45  * the {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}
     46  * interface extends the {@link SingletonBeanRegistry} interface.
     47  * <p>
     48  * <p>Note that this class assumes neither a bean definition concept
     49  * nor a specific creation process for bean instances, in contrast to
     50  * {@link AbstractBeanFactory} and {@link DefaultListableBeanFactory}
     51  * (which inherit from it). Can alternatively also be used as a nested
     52  * helper to delegate to.
     53  *
     54  * @author Juergen Hoeller
     55  * @see #registerSingleton
     56  * @see #registerDisposableBean
     57  * @see org.springframework.beans.factory.DisposableBean
     58  * @see org.springframework.beans.factory.config.ConfigurableBeanFactory
     59  * @since 2.0
     60  */
     61 public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
     62 
     63     /**
     64      * Internal marker for a null singleton object:
     65      * used as marker value for concurrent Maps (which don't support null values).
     66      * concurrent Maps里不能put null,所以用这个代替
     67      */
     68     protected static final Object NULL_OBJECT = new Object();
     69 
     70 
     71     /**
     72      * Logger available to subclasses
     73      */
     74     protected final Log logger = LogFactory.getLog(getClass());
     75 
     76     /**
     77      * Cache of singleton objects: bean name --> bean instance
     78      * 存单例的bean,FactoryBean也算
     79      */
     80     private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);
     81 
     82     /**
     83      * Cache of singleton factories: bean name --> ObjectFactory
     84      * 存ObjectFactory,我自己没用过.
     85      * 测试的时候发现有循环引用的时候.比如A,B相互引用的时候,先扫描到A注册A.当前工厂的一个内部类对象会被注册到这里.有1个bean的引用指向B
     86      */
     87     private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);
     88 
     89     /**
     90      * Cache of early singleton objects: bean name --> bean instance
     91      * 一般情况下可能这个map都是空的,只有2个bean相互引用的时候才会有值.
     92      * 看英文解释似乎是一个bean还没被完全创建完的时候会被丢到这个map里.可能作用是先让其他bean先能够引用这个bean吧
     93      * 测试A和B相互引用,先扫描到A的话A会放到这里里面,然后开始注册B,B注册完了再remove
     94      */
     95     private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);
     96 
     97     /**
     98      * Set of registered singletons, containing the bean names in registration order
     99      * 注册的bean的name都会放到这里
    100      */
    101     private final Set<String> registeredSingletons = new LinkedHashSet<String>(64);
    102 
    103     /**
    104      * Names of beans that are currently in creation
    105      * 注册A的时候如果A和B相互引用,A会被放到这里里面.和earlySingletonObjects一起使用
    106      */
    107     private final Set<String> singletonsCurrentlyInCreation =
    108             Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));
    109 
    110     /**
    111      * Names of beans currently excluded from in creation checks
    112      * 创建bean过程中有一些bean已经在创建了在创建会报错,用这个可以排除掉这个检查,不知道啥时候会用到
    113      */
    114     private final Set<String> inCreationCheckExclusions =
    115             Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));
    116 
    117     /**
    118      * List of suppressed Exceptions, available for associating related causes
    119      * 创建bean过程中出现一些特定的错误的时候可以无视这些错误继续创建
    120      */
    121     private Set<Exception> suppressedExceptions;
    122 
    123     /**
    124      * Flag that indicates whether we're currently within destroySingletons
    125      * 是否正在销毁bean,可能是factory在destroy的时候就不能再创建bean了
    126      */
    127     private boolean singletonsCurrentlyInDestruction = false;
    128 
    129     /**
    130      * Disposable bean instances: bean name --> disposable instance
    131      * 存disposableBean
    132      */
    133     private final Map<String, Object> disposableBeans = new LinkedHashMap<String, Object>();
    134 
    135     /**
    136      * Map between containing bean names: bean name --> Set of bean names that the bean contains
    137      * 似乎是用在innerbean和outerbean的时候使用.我一直没使用过这种bean
    138      */
    139     private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<String, Set<String>>(16);
    140 
    141     /**
    142      * Map between dependent bean names: bean name --> Set of dependent bean names
    143      * A中有B,那key就是B,value就是A.销毁B之前需要先销毁A
    144      */
    145     private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<String, Set<String>>(64);
    146 
    147     /**
    148      * Map between depending bean names: bean name --> Set of bean names for the bean's dependencies
    149      * 和dependentBeanMap刚好相反,A中有B和C的引用.那key是A value是B和C
    150      */
    151     private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<String, Set<String>>(64);
    152 
    153 
    154     /**
    155      * 注册单例bean
    156      *
    157      * @param beanName
    158      * @param singletonObject
    159      * @throws IllegalStateException
    160      */
    161     @Override
    162     public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
    163         Assert.notNull(beanName, "'beanName' must not be null");
    164         synchronized (this.singletonObjects) {
    165             Object oldObject = this.singletonObjects.get(beanName);
    166             // 从singletonObjects获取bean,有bean说明已经注册过了不让重新注册
    167             if (oldObject != null) {
    168                 throw new IllegalStateException("Could not register object [" + singletonObject +
    169                         "] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
    170             }
    171             // 没注册过就掉注册方法
    172             addSingleton(beanName, singletonObject);
    173         }
    174     }
    175 
    176     /**
    177      * Add the given singleton object to the singleton cache of this factory.
    178      * <p>To be called for eager registration of singletons.
    179      * 注册1个单例bean
    180      *
    181      * @param beanName        the name of the bean
    182      * @param singletonObject the singleton object
    183      */
    184     protected void addSingleton(String beanName, Object singletonObject) {
    185         synchronized (this.singletonObjects) {
    186             // 注册的单例bean放到singletonObjects和registeredSingletons里,null的话为了防止map抛出异常所以要put一个默认的obj
    187             // 但是我也不知道为什么时候add的时候singletonFactories和earlySingletonObjects会有值,需要remove.
    188             this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
    189             this.singletonFactories.remove(beanName);
    190             this.earlySingletonObjects.remove(beanName);
    191             this.registeredSingletons.add(beanName);
    192         }
    193     }
    194 
    195     /**
    196      * Add the given singleton factory for building the specified singleton
    197      * if necessary.
    198      * <p>To be called for eager registration of singletons, e.g. to be able to
    199      * resolve circular references.
    200      * 和addSingleton几乎一样的道理
    201      *
    202      * @param beanName         the name of the bean
    203      * @param singletonFactory the factory for the singleton object
    204      */
    205     protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
    206         Assert.notNull(singletonFactory, "Singleton factory must not be null");
    207         synchronized (this.singletonObjects) {
    208             if (!this.singletonObjects.containsKey(beanName)) {
    209                 this.singletonFactories.put(beanName, singletonFactory);
    210                 this.earlySingletonObjects.remove(beanName);
    211                 this.registeredSingletons.add(beanName);
    212             }
    213         }
    214     }
    215 
    216     @Override
    217     public Object getSingleton(String beanName) {
    218         return getSingleton(beanName, true);
    219     }
    220 
    221     /**
    222      * Return the (raw) singleton object registered under the given name.
    223      * <p>Checks already instantiated singletons and also allows for an early
    224      * reference to a currently created singleton (resolving a circular reference).
    225      * 获取一个单例
    226      *
    227      * @param beanName            the name of the bean to look for
    228      * @param allowEarlyReference whether early references should be created or not
    229      * @return the registered singleton object, or {@code null} if none found
    230      */
    231     protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    232         Object singletonObject = this.singletonObjects.get(beanName);
    233         // 从singletonObjects中先获取,如果非空就直接返回,如果是空的,判断是否正在创建中
    234         if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
    235             synchronized (this.singletonObjects) {
    236                 // 如果正在创建就从earlySingletonObjects中获取A,B相互引用先加载A的时候A会被先放到earlySingletonObjects中而不是singletonObjects中,因为A还没创建就需要创建B
    237                 singletonObject = this.earlySingletonObjects.get(beanName);
    238                 // 目前我还没遇到过allowEarlyReference为true的情况
    239                 if (singletonObject == null && allowEarlyReference) {
    240                     ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
    241                     if (singletonFactory != null) {
    242                         singletonObject = singletonFactory.getObject();
    243                         this.earlySingletonObjects.put(beanName, singletonObject);
    244                         this.singletonFactories.remove(beanName);
    245                     }
    246                 }
    247             }
    248         }
    249         return (singletonObject != NULL_OBJECT ? singletonObject : null);
    250     }
    251 
    252     /**
    253      * Return the (raw) singleton object registered under the given name,
    254      * creating and registering a new one if none registered yet.
    255      * 也是获取bean,但是没有的时候可以从工厂里获取
    256      *
    257      * @param beanName         the name of the bean
    258      * @param singletonFactory the ObjectFactory to lazily create the singleton
    259      *                         with, if necessary
    260      * @return the registered singleton object
    261      */
    262     public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
    263         Assert.notNull(beanName, "'beanName' must not be null");
    264         synchronized (this.singletonObjects) {
    265             // 获取bean
    266             Object singletonObject = this.singletonObjects.get(beanName);
    267             if (singletonObject == null) {
    268                 // 如果工厂正在destroy.就直接抛异常
    269                 if (this.singletonsCurrentlyInDestruction) {
    270                     throw new BeanCreationNotAllowedException(beanName,
    271                             "Singleton bean creation not allowed while the singletons of this factory are in destruction " +
    272                                     "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
    273                 }
    274                 if (logger.isDebugEnabled()) {
    275                     logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
    276                 }
    277                 // 创建之前做校验,如果已经正在创建了.就报错.
    278                 beforeSingletonCreation(beanName);
    279                 boolean newSingleton = false;
    280                 boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
    281                 if (recordSuppressedExceptions) {
    282                     this.suppressedExceptions = new LinkedHashSet<Exception>();
    283                 }
    284                 try {
    285                     // 从工厂里获取
    286                     singletonObject = singletonFactory.getObject();
    287                     newSingleton = true;
    288                 } catch (IllegalStateException ex) {
    289                     // Has the singleton object implicitly appeared in the meantime ->
    290                     // if yes, proceed with it since the exception indicates that state.
    291                     // 之前有 同步 不知道什么时候会进这条分支
    292                     singletonObject = this.singletonObjects.get(beanName);
    293                     if (singletonObject == null) {
    294                         throw ex;
    295                     }
    296                 } catch (BeanCreationException ex) {
    297                     // 如果创建报错了.就把之前抑制的错误一起抛出,不过这个方法里没看到有添加抑制错误的.
    298                     if (recordSuppressedExceptions) {
    299                         for (Exception suppressedException : this.suppressedExceptions) {
    300                             ex.addRelatedCause(suppressedException);
    301                         }
    302                     }
    303                     throw ex;
    304                 } finally {
    305                     if (recordSuppressedExceptions) {
    306                         this.suppressedExceptions = null;
    307                     }
    308                     // 把之前的singletonsCurrentlyInCreation添加的正在创建的bean删掉
    309                     afterSingletonCreation(beanName);
    310                 }
    311                 // 如果是新创建了bean就添加到相应的map里
    312                 if (newSingleton) {
    313                     addSingleton(beanName, singletonObject);
    314                 }
    315             }
    316             return (singletonObject != NULL_OBJECT ? singletonObject : null);
    317         }
    318     }
    319 
    320     /**
    321      * Register an Exception that happened to get suppressed during the creation of a
    322      * singleton bean instance, e.g. a temporary circular reference resolution problem.
    323      * 添加需要抑制的错误,创建过程中如果报了这些错误,不算出错.本类中没被调用
    324      *
    325      * @param ex the Exception to register
    326      */
    327     protected void onSuppressedException(Exception ex) {
    328         synchronized (this.singletonObjects) {
    329             if (this.suppressedExceptions != null) {
    330                 this.suppressedExceptions.add(ex);
    331             }
    332         }
    333     }
    334 
    335     /**
    336      * Remove the bean with the given name from the singleton cache of this factory,
    337      * to be able to clean up eager registration of a singleton if creation failed.
    338      * 移除一个单例bean
    339      *
    340      * @param beanName the name of the bean
    341      * @see #getSingletonMutex()
    342      */
    343     protected void removeSingleton(String beanName) {
    344         synchronized (this.singletonObjects) {
    345             this.singletonObjects.remove(beanName);
    346             this.singletonFactories.remove(beanName);
    347             this.earlySingletonObjects.remove(beanName);
    348             this.registeredSingletons.remove(beanName);
    349         }
    350     }
    351 
    352     @Override
    353     public boolean containsSingleton(String beanName) {
    354         return this.singletonObjects.containsKey(beanName);
    355     }
    356 
    357     @Override
    358     public String[] getSingletonNames() {
    359         synchronized (this.singletonObjects) {
    360             return StringUtils.toStringArray(this.registeredSingletons);
    361         }
    362     }
    363 
    364     @Override
    365     public int getSingletonCount() {
    366         synchronized (this.singletonObjects) {
    367             return this.registeredSingletons.size();
    368         }
    369     }
    370 
    371 
    372     /**
    373      * 设置一个bean正在被创建的标志,其实是放到一个跳过检查的set里.在这个set里的bean都会跳过检查.不然正在创建又执行创建需要抛出异常
    374      * @param beanName
    375      * @param inCreation
    376      */
    377     public void setCurrentlyInCreation(String beanName, boolean inCreation) {
    378         Assert.notNull(beanName, "Bean name must not be null");
    379         if (!inCreation) {
    380             this.inCreationCheckExclusions.add(beanName);
    381         } else {
    382             this.inCreationCheckExclusions.remove(beanName);
    383         }
    384     }
    385 
    386     public boolean isCurrentlyInCreation(String beanName) {
    387         Assert.notNull(beanName, "Bean name must not be null");
    388         return (!this.inCreationCheckExclusions.contains(beanName) && isActuallyInCreation(beanName));
    389     }
    390 
    391     /**
    392      * setCurrentlyInCreation方法只是用1个set集合记录需要跳过检查步骤的bean,singletonsCurrentlyInCreation里存的bean才是真正正在创建的bean
    393      * @param beanName
    394      * @return
    395      */
    396     protected boolean isActuallyInCreation(String beanName) {
    397         return isSingletonCurrentlyInCreation(beanName);
    398     }
    399 
    400     /**
    401      * Return whether the specified singleton bean is currently in creation
    402      * (within the entire factory).
    403      * 参考isActuallyInCreation方法
    404      *
    405      * @param beanName the name of the bean
    406      */
    407     public boolean isSingletonCurrentlyInCreation(String beanName) {
    408         return this.singletonsCurrentlyInCreation.contains(beanName);
    409     }
    410 
    411     /**
    412      * Callback before singleton creation.
    413      * <p>The default implementation register the singleton as currently in creation.
    414      * 在ObjectFactory创建bean之前检查一下是否已经正在创建这个bean了.
    415      *
    416      * @param beanName the name of the singleton about to be created
    417      * @see #isSingletonCurrentlyInCreation
    418      */
    419     protected void beforeSingletonCreation(String beanName) {
    420         if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
    421             throw new BeanCurrentlyInCreationException(beanName);
    422         }
    423     }
    424 
    425     /**
    426      * Callback after singleton creation.
    427      * <p>The default implementation marks the singleton as not in creation anymore.
    428      * 在ObjectFactory创建bean之后,需要这个bean正在创建的标志移除
    429      *
    430      * @param beanName the name of the singleton that has been created
    431      * @see #isSingletonCurrentlyInCreation
    432      */
    433     protected void afterSingletonCreation(String beanName) {
    434         if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
    435             throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
    436         }
    437     }
    438 
    439 
    440     /**
    441      * Add the given bean to the list of disposable beans in this registry.
    442      * <p>Disposable beans usually correspond to registered singletons,
    443      * matching the bean name but potentially being a different instance
    444      * (for example, a DisposableBean adapter for a singleton that does not
    445      * naturally implement Spring's DisposableBean interface).
    446      * 注册DisposableBean
    447      *
    448      * @param beanName the name of the bean
    449      * @param bean     the bean instance
    450      */
    451     public void registerDisposableBean(String beanName, DisposableBean bean) {
    452         synchronized (this.disposableBeans) {
    453             this.disposableBeans.put(beanName, bean);
    454         }
    455     }
    456 
    457     /**
    458      * Register a containment relationship between two beans,
    459      * e.g. between an inner bean and its containing outer bean.
    460      * <p>Also registers the containing bean as dependent on the contained bean
    461      * in terms of destruction order.
    462      * 注册嵌套的bean.我从来没用过.
    463      *
    464      * @param containedBeanName  the name of the contained (inner) bean 内部bean
    465      * @param containingBeanName the name of the containing (outer) bean 外部bean
    466      * @see #registerDependentBean
    467      */
    468     public void registerContainedBean(String containedBeanName, String containingBeanName) {
    469         // A quick check for an existing entry upfront, avoiding synchronization...
    470         Set<String> containedBeans = this.containedBeanMap.get(containingBeanName);
    471         if (containedBeans != null && containedBeans.contains(containedBeanName)) {
    472             return;
    473         }
    474 
    475         // No entry yet -> fully synchronized manipulation of the containedBeans Set
    476         synchronized (this.containedBeanMap) {
    477             containedBeans = this.containedBeanMap.get(containingBeanName);
    478             if (containedBeans == null) {
    479                 containedBeans = new LinkedHashSet<String>(8);
    480                 this.containedBeanMap.put(containingBeanName, containedBeans);
    481             }
    482             containedBeans.add(containedBeanName);
    483         }
    484         registerDependentBean(containedBeanName, containingBeanName);
    485     }
    486 
    487     /**
    488      * Register a dependent bean for the given bean,
    489      * to be destroyed before the given bean is destroyed.
    490      * 注册相互依赖的bean.比如A中有B.dependentBeanMap里key是B,value是A.需要先销毁A再销毁B
    491      * dependenciesForBeanMap刚好相反.可以参考之前成员域上的注释
    492      *
    493      * @param beanName          the name of the bean
    494      * @param dependentBeanName the name of the dependent bean
    495      */
    496     public void registerDependentBean(String beanName, String dependentBeanName) {
    497         // A quick check for an existing entry upfront, avoiding synchronization...
    498         // 先把别名转化到真正的bean name
    499         String canonicalName = canonicalName(beanName);
    500         Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
    501         if (dependentBeans != null && dependentBeans.contains(dependentBeanName)) {
    502             return;
    503         }
    504 
    505         // No entry yet -> fully synchronized manipulation of the dependentBeans Set
    506         // 依赖之前没注册过就注册到相应的map里去
    507         synchronized (this.dependentBeanMap) {
    508             dependentBeans = this.dependentBeanMap.get(canonicalName);
    509             if (dependentBeans == null) {
    510                 dependentBeans = new LinkedHashSet<String>(8);
    511                 this.dependentBeanMap.put(canonicalName, dependentBeans);
    512             }
    513             dependentBeans.add(dependentBeanName);
    514         }
    515         synchronized (this.dependenciesForBeanMap) {
    516             Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName);
    517             if (dependenciesForBean == null) {
    518                 dependenciesForBean = new LinkedHashSet<String>(8);
    519                 this.dependenciesForBeanMap.put(dependentBeanName, dependenciesForBean);
    520             }
    521             dependenciesForBean.add(canonicalName);
    522         }
    523     }
    524 
    525     /**
    526      * Determine whether the specified dependent bean has been registered as
    527      * dependent on the given bean or on any of its transitive dependencies.
    528      * 判断2个bean是否有依赖关系
    529      *
    530      * @param beanName          the name of the bean to check
    531      * @param dependentBeanName the name of the dependent bean
    532      * @since 4.0
    533      */
    534     protected boolean isDependent(String beanName, String dependentBeanName) {
    535         return isDependent(beanName, dependentBeanName, null);
    536     }
    537 
    538     /**
    539      * 判断2个bean是否有依赖关系,A中有B,B中有C,那C依赖A是true.
    540      * @param beanName
    541      * @param dependentBeanName
    542      * @param alreadySeen
    543      * @return
    544      */
    545     private boolean isDependent(String beanName, String dependentBeanName, Set<String> alreadySeen) {
    546         String canonicalName = canonicalName(beanName);
    547         if (alreadySeen != null && alreadySeen.contains(beanName)) {
    548             return false;
    549         }
    550         // canonicalName是C dependentBeans是B
    551         Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
    552         if (dependentBeans == null) {
    553             return false;
    554         }
    555         if (dependentBeans.contains(dependentBeanName)) {
    556             return true;
    557         }
    558         // 第一轮没找到A只找到包含B的一个set.所以再便利这个set.去看这个set里的bean是否依赖A,但是可能会有循环引用.所以找过的bean需要记录,不需要再找
    559         for (String transitiveDependency : dependentBeans) {
    560             if (alreadySeen == null) {
    561                 alreadySeen = new HashSet<String>();
    562             }
    563             alreadySeen.add(beanName); // 已经找过的bean放到这里.C已经找过了.
    564             if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) { // 递归调用,判断B是否依赖A,是true.而C依赖B,所以C依赖A
    565                 return true;
    566             }
    567         }
    568         return false;
    569     }
    570 
    571     /**
    572      * Determine whether a dependent bean has been registered for the given name.
    573      *
    574      * @param beanName the name of the bean to check
    575      */
    576     protected boolean hasDependentBean(String beanName) {
    577         return this.dependentBeanMap.containsKey(beanName);
    578     }
    579 
    580     /**
    581      * Return the names of all beans which depend on the specified bean, if any.
    582      *
    583      * @param beanName the name of the bean
    584      * @return the array of dependent bean names, or an empty array if none
    585      */
    586     public String[] getDependentBeans(String beanName) {
    587         Set<String> dependentBeans = this.dependentBeanMap.get(beanName);
    588         if (dependentBeans == null) {
    589             return new String[0];
    590         }
    591         return StringUtils.toStringArray(dependentBeans);
    592     }
    593 
    594     /**
    595      * Return the names of all beans that the specified bean depends on, if any.
    596      *
    597      * @param beanName the name of the bean
    598      * @return the array of names of beans which the bean depends on,
    599      * or an empty array if none
    600      */
    601     public String[] getDependenciesForBean(String beanName) {
    602         Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName);
    603         if (dependenciesForBean == null) {
    604             return new String[0];
    605         }
    606         return dependenciesForBean.toArray(new String[dependenciesForBean.size()]);
    607     }
    608 
    609     /**
    610      * 销毁单例bean
    611      */
    612     public void destroySingletons() {
    613         if (logger.isDebugEnabled()) {
    614             logger.debug("Destroying singletons in " + this);
    615         }
    616         // 设置正在销毁的标志
    617         synchronized (this.singletonObjects) {
    618             this.singletonsCurrentlyInDestruction = true;
    619         }
    620 
    621         String[] disposableBeanNames;
    622         synchronized (this.disposableBeans) {
    623             disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
    624         }
    625         // 取出所有disposableBeans然后调用每个bean都调用相应的销毁方法
    626         for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
    627             destroySingleton(disposableBeanNames[i]);
    628         }
    629 
    630         // 所有缓存清空
    631         this.containedBeanMap.clear();
    632         this.dependentBeanMap.clear();
    633         this.dependenciesForBeanMap.clear();
    634 
    635         synchronized (this.singletonObjects) {
    636             this.singletonObjects.clear();
    637             this.singletonFactories.clear();
    638             this.earlySingletonObjects.clear();
    639             this.registeredSingletons.clear();
    640             this.singletonsCurrentlyInDestruction = false;
    641         }
    642     }
    643 
    644     /**
    645      * Destroy the given bean. Delegates to {@code destroyBean}
    646      * if a corresponding disposable bean instance is found.
    647      *
    648      * @param beanName the name of the bean
    649      * @see #destroyBean
    650      */
    651     public void destroySingleton(String beanName) {
    652         // Remove a registered singleton of the given name, if any.
    653         removeSingleton(beanName);
    654 
    655         // Destroy the corresponding DisposableBean instance.
    656         DisposableBean disposableBean;
    657         synchronized (this.disposableBeans) {
    658             disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
    659         }
    660         destroyBean(beanName, disposableBean);
    661     }
    662 
    663     /**
    664      * Destroy the given bean. Must destroy beans that depend on the given
    665      * bean before the bean itself. Should not throw any exceptions.
    666      *
    667      * @param beanName the name of the bean
    668      * @param bean     the bean instance to destroy
    669      */
    670     protected void destroyBean(String beanName, DisposableBean bean) {
    671         // Trigger destruction of dependent beans first...
    672         // 销毁1个bean的时候需要按顺序,先销毁引用她的bean,再销毁他自己
    673         Set<String> dependencies = this.dependentBeanMap.remove(beanName);
    674         if (dependencies != null) {
    675             if (logger.isDebugEnabled()) {
    676                 logger.debug("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
    677             }
    678             for (String dependentBeanName : dependencies) {
    679                 //对于每个引用这个bean的所有bean,先销毁他们,再销毁当前这个beanName对应的bean,A中有B需要先销毁A
    680                 destroySingleton(dependentBeanName);
    681             }
    682         }
    683 
    684         // Actually destroy the bean now...
    685         if (bean != null) {
    686             try {
    687                 bean.destroy(); // DisposableBean接口的方法
    688             } catch (Throwable ex) {
    689                 logger.error("Destroy method on bean with name '" + beanName + "' threw an exception", ex);
    690             }
    691         }
    692 
    693         // Trigger destruction of contained beans...
    694         // 对于内部bean也一样,先销毁外部的bean
    695         Set<String> containedBeans = this.containedBeanMap.remove(beanName);
    696         if (containedBeans != null) {
    697             for (String containedBeanName : containedBeans) {
    698                 destroySingleton(containedBeanName);
    699             }
    700         }
    701 
    702         // Remove destroyed bean from other beans' dependencies.
    703         // 销毁了这个bean,那dependentBeanMap中如果其他bean依赖这个bean,就都可以移除这个bean的引用.比如A中有B和C类.destroyB的时候需要先destroy A
    704         // 那destroy A了以后因为C也依赖A.所以也要把dependentBeanMap的key c 对应的vaalue A也删除,不然下次删除C的时候又要删除A.这样就重复destroy A了.
    705         synchronized (this.dependentBeanMap) {
    706             for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext(); ) {
    707                 Map.Entry<String, Set<String>> entry = it.next();
    708                 Set<String> dependenciesToClean = entry.getValue();
    709                 dependenciesToClean.remove(beanName);
    710                 if (dependenciesToClean.isEmpty()) {
    711                     it.remove();
    712                 }
    713             }
    714         }
    715 
    716         // Remove destroyed bean's prepared dependency information.
    717         this.dependenciesForBeanMap.remove(beanName);
    718     }
    719 
    720     /**
    721      * Exposes the singleton mutex to subclasses and external collaborators.
    722      * <p>Subclasses should synchronize on the given Object if they perform
    723      * any sort of extended singleton creation phase. In particular, subclasses
    724      * should <i>not</i> have their own mutexes involved in singleton creation,
    725      * to avoid the potential for deadlocks in lazy-init situations.
    726      */
    727     public final Object getSingletonMutex() {
    728         return this.singletonObjects;
    729     }
    730 
    731 }
    View Code

    FactoryBeanRegistrySupport

    这个类基本上和它的父类DefaultSingletonBeanRegistry功能差不多.就是多了1个叫做factoryBeanObjectCache的map去缓存FactoryBean生成的bean...代码写法都大同小异..我想分享下期中的1个方法

     1     /**
     2      * Obtain an object to expose from the given FactoryBean.
     3      *
     4      * @param factory           the FactoryBean instance
     5      * @param beanName          the name of the bean
     6      * @param shouldPostProcess whether the bean is subject to post-processing
     7      * @return the object obtained from the FactoryBean
     8      * @throws BeanCreationException if FactoryBean object creation failed
     9      * @see org.springframework.beans.factory.FactoryBean#getObject()
    10      */
    11     protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
    12         if (factory.isSingleton() && containsSingleton(beanName)) { // FactoryBean返回的对象是单例并且FactoryBean(不是返回的对象)这个bean已经在缓存中了
    13             synchronized (getSingletonMutex()) {
    14                 Object object = this.factoryBeanObjectCache.get(beanName); // 从缓存里拿FactoryBean的返回对象
    15                 if (object == null) { // 没缓存的话
    16                     object = doGetObjectFromFactoryBean(factory, beanName); // 就重新生成
    17                     // Only post-process and store if not put there already during getObject() call above
    18                     // (e.g. because of circular reference processing triggered by custom getBean calls)
    19                     Object alreadyThere = this.factoryBeanObjectCache.get(beanName); // 不懂为什么上面去过一次是null了需要再取几次...什么时候会发生呢?
    20                     if (alreadyThere != null) {
    21                         object = alreadyThere;
    22                     } else {
    23                         if (object != null && shouldPostProcess) {
    24                             try {
    25                                 object = postProcessObjectFromFactoryBean(object, beanName); // 后置处理
    26                             } catch (Throwable ex) {
    27                                 throw new BeanCreationException(beanName,
    28                                         "Post-processing of FactoryBean's singleton object failed", ex);
    29                             }
    30                         }
    31                         this.factoryBeanObjectCache.put(beanName, (object != null ? object : NULL_OBJECT));
    32                     }
    33                 }
    34                 return (object != NULL_OBJECT ? object : null);
    35             }
    36         } else { // 不是单例,或者第一次调用FactoryBean不再缓存中
    37             Object object = doGetObjectFromFactoryBean(factory, beanName); // 从FactoryBean里生成
    38             if (object != null && shouldPostProcess) {
    39                 try {
    40                     object = postProcessObjectFromFactoryBean(object, beanName); // 后置处理
    41                 } catch (Throwable ex) {
    42                     throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
    43                 }
    44             }
    45             return object;
    46         }
    47     }

    对比它的父类里的一些map....

    factoryBeanObjectCache里存的是BeanFactory的getObject返回的对象.

    singletonObjects里存一般的单例和BeanFactory对象.

    然后不管是BeanFactory还是BeanFactory返回的对象.beanname都是不带&,这点和使用BeanFactory的getBean方法不太一样...等看到后面的BF可能就清楚为什么了.

    另外postProcessObjectFromFactoryBean这个方法在当前类里仅仅返回传入参数object.但是是个protected的方法,子类肯定会去重写的.这个方法不出意外应该就是BeanPostProcessor参与Spring声明周期的地方(对于FactoryBean来说).

    一个小测试:

     1 package spring.bf;
     2 
     3 import org.junit.Test;
     4 import org.junit.runner.RunWith;
     5 import org.springframework.beans.BeansException;
     6 import org.springframework.beans.factory.FactoryBean;
     7 import org.springframework.beans.factory.annotation.Autowired;
     8 import org.springframework.beans.factory.annotation.Qualifier;
     9 import org.springframework.beans.factory.config.BeanPostProcessor;
    10 import org.springframework.stereotype.Component;
    11 import org.springframework.test.context.ContextConfiguration;
    12 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    13 
    14 @RunWith(SpringJUnit4ClassRunner.class)
    15 @ContextConfiguration("classpath:test-application-context.xml")
    16 public class FactoryBeanRegistrySupportTest {
    17 
    18     @Autowired
    19     @Qualifier("factoryBeanRegistrySupportTest_FactoryBean")
    20     Object o;
    21 
    22     /**
    23      * 测试BeanFactory和BeanPostProcessor
    24      */
    25     @Test
    26     public void test1() {
    27         System.out.println(o);
    28     }
    29 }
    30 
    31 
    32 @Component
    33 class FactoryBeanRegistrySupportTest_FactoryBean implements FactoryBean<Object> {
    34 
    35     private Object a = new Object();
    36 
    37     @Override
    38     public Object getObject() throws Exception {
    39         return a;
    40     }
    41 
    42     @Override
    43     public Class<?> getObjectType() {
    44         return Object.class;
    45     }
    46 
    47     @Override
    48     public boolean isSingleton() {
    49         return true;
    50     }
    51 }
    52 
    53 @Component
    54 class FactoryBeanRegistrySupportTest_PostProcess implements BeanPostProcessor {
    55 
    56     private static final String name = "factoryBeanRegistrySupportTest_FactoryBean";
    57 
    58     @Override
    59     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    60         if (beanName.equals(name)) {
    61             System.out.println("postProcessBeforeInitialization ->" + beanName);
    62         }
    63         return bean;
    64     }
    65 
    66     @Override
    67     public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    68         if (beanName.equals(name)) {
    69             System.out.println("postProcessAfterInitialization ->" + beanName);
    70         }
    71         return bean;
    72     }
    73 }

    输出:

    postProcessBeforeInitialization ->factoryBeanRegistrySupportTest_FactoryBean 这个是FactoryBean作为单例被new的时候做的
    postProcessAfterInitialization ->factoryBeanRegistrySupportTest_FactoryBean 这个是FactoryBean作为单例被new的时候做的
    postProcessAfterInitialization ->factoryBeanRegistrySupportTest_FactoryBean 这个是FactoryBean的getObject返回的对象做的
    java.lang.Object@f1e3986 输出getObject返回的对象

    那么为什么FactoryBean的返回对象不要做postProcessBeforeInitialization,只做了postProcessAfterInitialization  呢??? 为什么这样设定???  不太懂.

    我觉得.可能是其他bean的afterProperties可能会扫描一些特性的bean做处理..这里工厂返回的bean肯定没有被之前扫描到.而postProcessBeforeInitialization是要在afterProperties之前做的(对于单个bean来说).所以这里不再执行.

    AbstractBeanFactory

       1 /*
       2  * Copyright 2002-2015 the original author or authors.
       3  *
       4  * Licensed under the Apache License, Version 2.0 (the "License");
       5  * you may not use this file except in compliance with the License.
       6  * You may obtain a copy of the License at
       7  *
       8  *      http://www.apache.org/licenses/LICENSE-2.0
       9  *
      10  * Unless required by applicable law or agreed to in writing, software
      11  * distributed under the License is distributed on an "AS IS" BASIS,
      12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      13  * See the License for the specific language governing permissions and
      14  * limitations under the License.
      15  */
      16 
      17 package org.springframework.beans.factory.support;
      18 
      19 import org.springframework.beans.*;
      20 import org.springframework.beans.factory.*;
      21 import org.springframework.beans.factory.config.*;
      22 import org.springframework.core.DecoratingClassLoader;
      23 import org.springframework.core.NamedThreadLocal;
      24 import org.springframework.core.convert.ConversionService;
      25 import org.springframework.util.*;
      26 
      27 import java.beans.PropertyEditor;
      28 import java.security.*;
      29 import java.util.*;
      30 import java.util.concurrent.ConcurrentHashMap;
      31 
      32 /**
      33  * Abstract base class for {@link org.springframework.beans.factory.BeanFactory}
      34  * implementations, providing the full capabilities of the
      35  * {@link org.springframework.beans.factory.config.ConfigurableBeanFactory} SPI.
      36  * Does <i>not</i> assume a listable bean factory: can therefore also be used
      37  * as base class for bean factory implementations which obtain bean definitions
      38  * from some backend resource (where bean definition access is an expensive operation).
      39  * <p>
      40  * <p>This class provides a singleton cache (through its base class
      41  * {@link org.springframework.beans.factory.support.DefaultSingletonBeanRegistry},
      42  * singleton/prototype determination, {@link org.springframework.beans.factory.FactoryBean}
      43  * handling, aliases, bean definition merging for child bean definitions,
      44  * and bean destruction ({@link org.springframework.beans.factory.DisposableBean}
      45  * interface, custom destroy methods). Furthermore, it can manage a bean factory
      46  * hierarchy (delegating to the parent in case of an unknown bean), through implementing
      47  * the {@link org.springframework.beans.factory.HierarchicalBeanFactory} interface.
      48  * <p>
      49  * <p>The main template methods to be implemented by subclasses are
      50  * {@link #getBeanDefinition} and {@link #createBean}, retrieving a bean definition
      51  * for a given bean name and creating a bean instance for a given bean definition,
      52  * respectively. Default implementations of those operations can be found in
      53  * {@link DefaultListableBeanFactory} and {@link AbstractAutowireCapableBeanFactory}.
      54  *
      55  * @author Rod Johnson
      56  * @author Juergen Hoeller
      57  * @author Costin Leau
      58  * @author Chris Beams
      59  * @see #getBeanDefinition
      60  * @see #createBean
      61  * @see AbstractAutowireCapableBeanFactory#createBean
      62  * @see DefaultListableBeanFactory#getBeanDefinition
      63  * @since 15 April 2001
      64  */
      65 public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
      66 
      67     /**
      68      * Parent bean factory, for bean inheritance support
      69      */
      70     private BeanFactory parentBeanFactory;
      71 
      72     /**
      73      * ClassLoader to resolve bean class names with, if necessary
      74      */
      75     private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
      76 
      77     /**
      78      * ClassLoader to temporarily resolve bean class names with, if necessary
      79      */
      80     private ClassLoader tempClassLoader;
      81 
      82     /**
      83      * Whether to cache bean metadata or rather reobtain it for every access
      84      */
      85     private boolean cacheBeanMetadata = true;
      86 
      87     /**
      88      * Resolution strategy for expressions in bean definition values
      89      */
      90     private BeanExpressionResolver beanExpressionResolver;
      91 
      92     /**
      93      * Spring ConversionService to use instead of PropertyEditors
      94      */
      95     private ConversionService conversionService;
      96 
      97     /**
      98      * Custom PropertyEditorRegistrars to apply to the beans of this factory
      99      */
     100     private final Set<PropertyEditorRegistrar> propertyEditorRegistrars =
     101             new LinkedHashSet<PropertyEditorRegistrar>(4);
     102 
     103     /**
     104      * A custom TypeConverter to use, overriding the default PropertyEditor mechanism
     105      */
     106     private TypeConverter typeConverter;
     107 
     108     /**
     109      * Custom PropertyEditors to apply to the beans of this factory
     110      */
     111     private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors =
     112             new HashMap<Class<?>, Class<? extends PropertyEditor>>(4);
     113 
     114     /**
     115      * String resolvers to apply e.g. to annotation attribute values
     116      */
     117     private final List<StringValueResolver> embeddedValueResolvers = new LinkedList<StringValueResolver>();
     118 
     119     /**
     120      * BeanPostProcessors to apply in createBean
     121      */
     122     private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();
     123 
     124     /**
     125      * Indicates whether any InstantiationAwareBeanPostProcessors have been registered
     126      */
     127     private boolean hasInstantiationAwareBeanPostProcessors;
     128 
     129     /**
     130      * Indicates whether any DestructionAwareBeanPostProcessors have been registered
     131      */
     132     private boolean hasDestructionAwareBeanPostProcessors;
     133 
     134     /**
     135      * Map from scope identifier String to corresponding Scope
     136      */
     137     private final Map<String, Scope> scopes = new LinkedHashMap<String, Scope>(8);
     138 
     139     /**
     140      * Security context used when running with a SecurityManager
     141      */
     142     private SecurityContextProvider securityContextProvider;
     143 
     144     /**
     145      * Map from bean name to merged RootBeanDefinition
     146      */
     147     private final Map<String, RootBeanDefinition> mergedBeanDefinitions =
     148             new ConcurrentHashMap<String, RootBeanDefinition>(64);
     149 
     150     /**
     151      * Names of beans that have already been created at least once
     152      */
     153     private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(64));
     154 
     155     /**
     156      * Names of beans that are currently in creation
     157      */
     158     private final ThreadLocal<Object> prototypesCurrentlyInCreation =
     159             new NamedThreadLocal<Object>("Prototype beans currently in creation");
     160 
     161 
     162     /**
     163      * Create a new AbstractBeanFactory.
     164      */
     165     public AbstractBeanFactory() {
     166     }
     167 
     168     /**
     169      * Create a new AbstractBeanFactory with the given parent.
     170      *
     171      * @param parentBeanFactory parent bean factory, or {@code null} if none
     172      * @see #getBean
     173      */
     174     public AbstractBeanFactory(BeanFactory parentBeanFactory) {
     175         this.parentBeanFactory = parentBeanFactory;
     176     }
     177 
     178 
     179     //---------------------------------------------------------------------
     180     // Implementation of BeanFactory interface
     181     //---------------------------------------------------------------------
     182 
     183     @Override
     184     public Object getBean(String name) throws BeansException {
     185         return doGetBean(name, null, null, false);
     186     }
     187 
     188     @Override
     189     public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
     190         return doGetBean(name, requiredType, null, false);
     191     }
     192 
     193     @Override
     194     public Object getBean(String name, Object... args) throws BeansException {
     195         return doGetBean(name, null, args, false);
     196     }
     197 
     198     /**
     199      * Return an instance, which may be shared or independent, of the specified bean.
     200      *
     201      * @param name         the name of the bean to retrieve
     202      * @param requiredType the required type of the bean to retrieve
     203      * @param args         arguments to use when creating a bean instance using explicit arguments
     204      *                     (only applied when creating a new instance as opposed to retrieving an existing one)
     205      * @return an instance of the bean
     206      * @throws BeansException if the bean could not be created
     207      */
     208     public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException {
     209         return doGetBean(name, requiredType, args, false);
     210     }
     211 
     212     /**
     213      * Return an instance, which may be shared or independent, of the specified bean.
     214      *
     215      * @param name          the name of the bean to retrieve
     216      * @param requiredType  the required type of the bean to retrieve
     217      * @param args          arguments to use when creating a bean instance using explicit arguments
     218      *                      (only applied when creating a new instance as opposed to retrieving an existing one)
     219      * @param typeCheckOnly whether the instance is obtained for a type check,
     220      *                      not for actual use
     221      * @return an instance of the bean
     222      * @throws BeansException if the bean could not be created
     223      */
     224     @SuppressWarnings("unchecked")
     225     protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {
     226 
     227         // 别名转化成bean的名字,同时有&的话直接去掉
     228         final String beanName = transformedBeanName(name);
     229         Object bean;
     230 
     231         // Eagerly check singleton cache for manually registered singletons.
     232         // 可能会是FactoryBean
     233         Object sharedInstance = getSingleton(beanName);
     234         if (sharedInstance != null && args == null) {
     235             if (logger.isDebugEnabled()) {
     236                 if (isSingletonCurrentlyInCreation(beanName)) {
     237                     logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
     238                             "' that is not fully initialized yet - a consequence of a circular reference");
     239                 } else {
     240                     logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
     241                 }
     242             }
     243             // 如果是FactoryBean就调用getObject,否则就返回那个bean
     244             bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
     245         } else { // 有可能是prototype bean
     246             // Fail if we're already creating this bean instance:
     247             // We're assumably within a circular reference.
     248             // 如果当前线程已经在创建个bean了.就抛出异常
     249             if (isPrototypeCurrentlyInCreation(beanName)) {
     250                 throw new BeanCurrentlyInCreationException(beanName);
     251             }
     252 
     253             // Check if bean definition exists in this factory.
     254             BeanFactory parentBeanFactory = getParentBeanFactory();
     255             // 如果这个bean的配置定义在父BF中的,即当前BF没有这个bean的配置信息
     256             if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
     257                 // Not found -> check parent.
     258                 // 转化别名成bean的实际名字,但是不会去掉&
     259                 String nameToLookup = originalBeanName(name);
     260                 // 调用父BF的getBean方法去获取bean.
     261                 if (args != null) {
     262                     // Delegation to parent with explicit args.
     263                     return (T) parentBeanFactory.getBean(nameToLookup, args);
     264                 } else {
     265                     // No args -> delegate to standard getBean method.
     266                     return parentBeanFactory.getBean(nameToLookup, requiredType);
     267                 }
     268             }
     269 
     270             if (!typeCheckOnly) {
     271                 // 标记这个bean已被创建
     272                 markBeanAsCreated(beanName);
     273             }
     274 
     275             try {
     276                 // 获取BeanDefinition
     277                 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
     278                 // 检测这个bean是不是abstract的
     279                 checkMergedBeanDefinition(mbd, beanName, args);
     280 
     281                 // Guarantee initialization of beans that the current bean depends on.
     282                 // A中有B,C,dependsOn=B,C
     283                 String[] dependsOn = mbd.getDependsOn();
     284                 if (dependsOn != null) {
     285                     for (String dependsOnBean : dependsOn) { // B和C
     286                         // 如果dependsOnBean中有beanName域.而mbd.getDependsOn();说明beanName中有dependsOnBean,所以是相互依赖
     287                         if (isDependent(beanName, dependsOnBean)) { // 为true说明B,C中也有A,而外层的mbd.getDependsOn();说明A中有B,C,所以循环引用
     288                             throw new BeanCreationException(mbd.getResourceDescription(), beanName,
     289                                     "Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
     290                         }
     291                         // beanName中有dependsOnBean,beanName依赖于dependsOnBean
     292                         registerDependentBean(dependsOnBean, beanName);
     293                         // 先初始化成员域的bean
     294                         getBean(dependsOnBean);
     295                     }
     296                 }
     297 
     298                 // Create bean instance.
     299                 // 如果是单例
     300                 if (mbd.isSingleton()) {
     301                     // 获取这个bean,没创建就创建
     302                     sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
     303                         @Override
     304                         public Object getObject() throws BeansException {
     305                             try {
     306                                 return createBean(beanName, mbd, args);
     307                             } catch (BeansException ex) {
     308                                 // Explicitly remove instance from singleton cache: It might have been put there
     309                                 // eagerly by the creation process, to allow for circular reference resolution.
     310                                 // Also remove any beans that received a temporary reference to the bean.
     311                                 destroySingleton(beanName);
     312                                 throw ex;
     313                             }
     314                         }
     315                     });
     316                     // 如果是FactoryBean就调用getObject,否则就返回那个bean
     317                     bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
     318                 } else if (mbd.isPrototype()) { // 如果是原型bean
     319                     // It's a prototype -> create a new instance.
     320                     Object prototypeInstance = null;
     321                     try {
     322                         // 记录正在创建的原型bean,这个bean和线程绑定
     323                         beforePrototypeCreation(beanName);
     324                         prototypeInstance = createBean(beanName, mbd, args);
     325                     } finally {
     326                         // 创建完毕,移除这个标记
     327                         afterPrototypeCreation(beanName);
     328                     }
     329                     // 如果是FactoryBean就调用getObject,否则就返回那个bean
     330                     bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
     331                 } else {
     332                     // 既不是单例又不是原型
     333                     String scopeName = mbd.getScope();
     334                     final Scope scope = this.scopes.get(scopeName);
     335                     if (scope == null) {
     336                         throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'");
     337                     }
     338                     try {
     339                         Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
     340                             @Override
     341                             public Object getObject() throws BeansException {
     342                                 beforePrototypeCreation(beanName);
     343                                 try {
     344                                     return createBean(beanName, mbd, args);
     345                                 } finally {
     346                                     afterPrototypeCreation(beanName);
     347                                 }
     348                             }
     349                         });
     350                         bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
     351                     } catch (IllegalStateException ex) {
     352                         throw new BeanCreationException(beanName,
     353                                 "Scope '" + scopeName + "' is not active for the current thread; " +
     354                                         "consider defining a scoped proxy for this bean if you intend to refer to it from a singleton",
     355                                 ex);
     356                     }
     357                 }
     358             } catch (BeansException ex) {
     359                 // 创建出错.
     360                 // 因为之前调用过markBeanAsCreated(beanName);标记过bean被创建,实际是失败的,所以要移除这个标记
     361                 cleanupAfterBeanCreationFailure(beanName);
     362                 throw ex;
     363             }
     364         }
     365 
     366         // Check if required type matches the type of the actual bean instance.
     367         // 讲前面得到的bean进行类型转化并返回
     368         if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
     369             try {
     370                 return getTypeConverter().convertIfNecessary(bean, requiredType);
     371             } catch (TypeMismatchException ex) {
     372                 if (logger.isDebugEnabled()) {
     373                     logger.debug("Failed to convert bean '" + name + "' to required type [" +
     374                             ClassUtils.getQualifiedName(requiredType) + "]", ex);
     375                 }
     376                 throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
     377             }
     378         }
     379         return (T) bean;
     380     }
     381 
     382     @Override
     383     public boolean containsBean(String name) {
     384         String beanName = transformedBeanName(name);
     385         if (containsSingleton(beanName) || containsBeanDefinition(beanName)) {
     386             // &开头或者是FactoryBean的实例
     387             return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name));
     388         }
     389         // Not found -> check parent.
     390         // 本BF找不到就找父类的
     391         BeanFactory parentBeanFactory = getParentBeanFactory();
     392         return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name)));
     393     }
     394 
     395     @Override
     396     public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
     397         String beanName = transformedBeanName(name); // 去掉&并且将alias转化成真正的beanname
     398 
     399         Object beanInstance = getSingleton(beanName, false); // 取到singleton
     400         if (beanInstance != null) {
     401             if (beanInstance instanceof FactoryBean) { // 如果bean是FactoryBean.
     402                 // &开头为true(取工厂bean)或者FactoryBean的isSingleton返回为true(不是&开头,取工厂的getObject返回)
     403                 return (BeanFactoryUtils.isFactoryDereference(name) || ((FactoryBean<?>) beanInstance).isSingleton());
     404             } else { // 不是工厂bean的情况下,不是&开头返回ture,就是最一般的单例bean.
     405                 return !BeanFactoryUtils.isFactoryDereference(name);
     406             }
     407         } else if (containsSingleton(beanName)) { // 不知道什么时候会进,getSingleton,但是containsSingleton为true.可能是abstract的bean吧
     408             return true;
     409         } else {
     410             // No singleton instance found -> check bean definition.
     411             BeanFactory parentBeanFactory = getParentBeanFactory();
     412             if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
     413                 // No bean definition found in this factory -> delegate to parent.
     414                 // 本BF没有这个bean的定义的话可以去找父类的.
     415                 return parentBeanFactory.isSingleton(originalBeanName(name));
     416             }
     417 
     418             // 合并父类和本身的bean定义
     419             RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
     420 
     421             // In case of FactoryBean, return singleton status of created object if not a dereference.
     422             if (mbd.isSingleton()) { // 定义中是单例,在判断是不是工厂
     423                 if (isFactoryBean(beanName, mbd)) { // 是工厂的话并且是不带&的话需要调用工厂的isSingleton方法
     424                     if (BeanFactoryUtils.isFactoryDereference(name)) {
     425                         return true;
     426                     }
     427                     FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
     428                     return factoryBean.isSingleton();
     429                 } else { // 不是工厂bean就是true
     430                     return !BeanFactoryUtils.isFactoryDereference(name);
     431                 }
     432             } else {
     433                 return false;
     434             }
     435         }
     436     }
     437 
     438     @Override
     439     public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
     440         String beanName = transformedBeanName(name);
     441 
     442         BeanFactory parentBeanFactory = getParentBeanFactory();
     443         if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
     444             // No bean definition found in this factory -> delegate to parent.
     445             // 本BF中没有这个bean的定义就找父工厂
     446             return parentBeanFactory.isPrototype(originalBeanName(name));
     447         }
     448 
     449         // 合并父BF和本BF得到bean的定义
     450         RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
     451         if (mbd.isPrototype()) { // bean的定义是原型,并且取不带&的bean,那就是原型对象为true,如果取&的bean,那需要返回的是工厂,如果是FactoryBean
     452             // In case of FactoryBean, return singleton status of created object if not a dereference.
     453             return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd));
     454         } else {
     455             // Singleton or scoped - not a prototype.
     456             // However, FactoryBean may still produce a prototype object...
     457             // 如果是&开头取工厂就直接返回false
     458             if (BeanFactoryUtils.isFactoryDereference(name)) {
     459                 return false;
     460             }
     461             // 不是&开头的话要看工厂的isSingleton或者isPrototype
     462             if (isFactoryBean(beanName, mbd)) {
     463                 final FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
     464                 if (System.getSecurityManager() != null) {
     465                     return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
     466                         @Override
     467                         public Boolean run() {
     468                             return ((factoryBean instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factoryBean).isPrototype()) ||
     469                                     !factoryBean.isSingleton());
     470                         }
     471                     }, getAccessControlContext());
     472                 } else {
     473                     return ((factoryBean instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factoryBean).isPrototype()) ||
     474                             !factoryBean.isSingleton());
     475                 }
     476             } else {
     477                 return false;
     478             }
     479         }
     480     }
     481 
     482     @Override
     483     public boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException {
     484         String beanName = transformedBeanName(name);
     485         Class<?> typeToMatch = (targetType != null ? targetType : Object.class);
     486 
     487         // Check manually registered singletons.
     488         Object beanInstance = getSingleton(beanName, false);
     489         if (beanInstance != null) {
     490             if (beanInstance instanceof FactoryBean) {
     491                 if (!BeanFactoryUtils.isFactoryDereference(name)) { // 取工厂的返回
     492                     Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance);
     493                     return (type != null && ClassUtils.isAssignable(typeToMatch, type));
     494                 } else { // 取工厂bean
     495                     return ClassUtils.isAssignableValue(typeToMatch, beanInstance);
     496                 }
     497             } else { // 取一般的bean
     498                 return !BeanFactoryUtils.isFactoryDereference(name) &&
     499                         ClassUtils.isAssignableValue(typeToMatch, beanInstance);
     500             }
     501         } else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
     502             // null instance registered
     503             return false;
     504         } else {
     505             // No singleton instance found -> check bean definition.
     506             BeanFactory parentBeanFactory = getParentBeanFactory();
     507             if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
     508                 // No bean definition found in this factory -> delegate to parent.
     509                 return parentBeanFactory.isTypeMatch(originalBeanName(name), targetType);
     510             }
     511 
     512             // Retrieve corresponding bean definition.
     513             RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
     514 
     515             Class<?>[] typesToMatch = (FactoryBean.class.equals(typeToMatch) ?
     516                     new Class<?>[]{typeToMatch} : new Class<?>[]{FactoryBean.class, typeToMatch});
     517 
     518             // Check decorated bean definition, if any: We assume it'll be easier
     519             // to determine the decorated bean's type than the proxy's type.
     520             BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
     521             if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
     522                 RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
     523                 Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);
     524                 if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
     525                     return typeToMatch.isAssignableFrom(targetClass);
     526                 }
     527             }
     528 
     529             Class<?> beanType = predictBeanType(beanName, mbd, typesToMatch);
     530             if (beanType == null) {
     531                 return false;
     532             }
     533 
     534             // Check bean class whether we're dealing with a FactoryBean.
     535             if (FactoryBean.class.isAssignableFrom(beanType)) {
     536                 if (!BeanFactoryUtils.isFactoryDereference(name)) {
     537                     // If it's a FactoryBean, we want to look at what it creates, not the factory class.
     538                     beanType = getTypeForFactoryBean(beanName, mbd);
     539                     if (beanType == null) {
     540                         return false;
     541                     }
     542                 }
     543             } else if (BeanFactoryUtils.isFactoryDereference(name)) {
     544                 // Special case: A SmartInstantiationAwareBeanPostProcessor returned a non-FactoryBean
     545                 // type but we nevertheless are being asked to dereference a FactoryBean...
     546                 // Let's check the original bean class and proceed with it if it is a FactoryBean.
     547                 beanType = predictBeanType(beanName, mbd, FactoryBean.class);
     548                 if (beanType == null || !FactoryBean.class.isAssignableFrom(beanType)) {
     549                     return false;
     550                 }
     551             }
     552 
     553             return typeToMatch.isAssignableFrom(beanType);
     554         }
     555     }
     556 
     557     @Override
     558     public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
     559         String beanName = transformedBeanName(name);
     560 
     561         // Check manually registered singletons.
     562         Object beanInstance = getSingleton(beanName, false);
     563         if (beanInstance != null) {
     564             if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
     565                 return getTypeForFactoryBean((FactoryBean<?>) beanInstance);
     566             } else {
     567                 return beanInstance.getClass();
     568             }
     569         } else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
     570             // null instance registered
     571             return null;
     572         } else {
     573             // No singleton instance found -> check bean definition.
     574             BeanFactory parentBeanFactory = getParentBeanFactory();
     575             if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
     576                 // No bean definition found in this factory -> delegate to parent.
     577                 return parentBeanFactory.getType(originalBeanName(name));
     578             }
     579 
     580             RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
     581 
     582             // Check decorated bean definition, if any: We assume it'll be easier
     583             // to determine the decorated bean's type than the proxy's type.
     584             BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
     585             if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
     586                 RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
     587                 Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd);
     588                 if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
     589                     return targetClass;
     590                 }
     591             }
     592 
     593             Class<?> beanClass = predictBeanType(beanName, mbd);
     594 
     595             // Check bean class whether we're dealing with a FactoryBean.
     596             if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) {
     597                 if (!BeanFactoryUtils.isFactoryDereference(name)) {
     598                     // If it's a FactoryBean, we want to look at what it creates, not at the factory class.
     599                     return getTypeForFactoryBean(beanName, mbd);
     600                 } else {
     601                     return beanClass;
     602                 }
     603             } else {
     604                 return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null);
     605             }
     606         }
     607     }
     608 
     609     /**
     610      * 覆盖了父类方法,增加了对FactoryBean的支持
     611      *
     612      * @param name
     613      * @return
     614      */
     615     @Override
     616     public String[] getAliases(String name) {
     617         String beanName = transformedBeanName(name);
     618         List<String> aliases = new ArrayList<String>();
     619         boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX);
     620         String fullBeanName = beanName;
     621         if (factoryPrefix) {
     622             fullBeanName = FACTORY_BEAN_PREFIX + beanName;
     623         }
     624         if (!fullBeanName.equals(name)) {
     625             aliases.add(fullBeanName);
     626         }
     627         String[] retrievedAliases = super.getAliases(beanName);
     628         for (String retrievedAlias : retrievedAliases) {
     629             String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") + retrievedAlias;
     630             if (!alias.equals(name)) {
     631                 aliases.add(alias);
     632             }
     633         }
     634         if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
     635             BeanFactory parentBeanFactory = getParentBeanFactory();
     636             if (parentBeanFactory != null) {
     637                 aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName)));
     638             }
     639         }
     640         return StringUtils.toStringArray(aliases);
     641     }
     642 
     643 
     644     //---------------------------------------------------------------------
     645     // Implementation of HierarchicalBeanFactory interface
     646     //---------------------------------------------------------------------
     647 
     648     @Override
     649     public BeanFactory getParentBeanFactory() {
     650         return this.parentBeanFactory;
     651     }
     652 
     653     @Override
     654     public boolean containsLocalBean(String name) {
     655         String beanName = transformedBeanName(name);
     656         return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) &&
     657                 (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName)));
     658     }
     659 
     660 
     661     //---------------------------------------------------------------------
     662     // Implementation of ConfigurableBeanFactory interface
     663     //---------------------------------------------------------------------
     664 
     665     @Override
     666     public void setParentBeanFactory(BeanFactory parentBeanFactory) {
     667         if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) {
     668             throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory);
     669         }
     670         this.parentBeanFactory = parentBeanFactory;
     671     }
     672 
     673     @Override
     674     public void setBeanClassLoader(ClassLoader beanClassLoader) {
     675         this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader());
     676     }
     677 
     678     @Override
     679     public ClassLoader getBeanClassLoader() {
     680         return this.beanClassLoader;
     681     }
     682 
     683     @Override
     684     public void setTempClassLoader(ClassLoader tempClassLoader) {
     685         this.tempClassLoader = tempClassLoader;
     686     }
     687 
     688     @Override
     689     public ClassLoader getTempClassLoader() {
     690         return this.tempClassLoader;
     691     }
     692 
     693     @Override
     694     public void setCacheBeanMetadata(boolean cacheBeanMetadata) {
     695         this.cacheBeanMetadata = cacheBeanMetadata;
     696     }
     697 
     698     @Override
     699     public boolean isCacheBeanMetadata() {
     700         return this.cacheBeanMetadata;
     701     }
     702 
     703     @Override
     704     public void setBeanExpressionResolver(BeanExpressionResolver resolver) {
     705         this.beanExpressionResolver = resolver;
     706     }
     707 
     708     @Override
     709     public BeanExpressionResolver getBeanExpressionResolver() {
     710         return this.beanExpressionResolver;
     711     }
     712 
     713     @Override
     714     public void setConversionService(ConversionService conversionService) {
     715         this.conversionService = conversionService;
     716     }
     717 
     718     @Override
     719     public ConversionService getConversionService() {
     720         return this.conversionService;
     721     }
     722 
     723     @Override
     724     public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) {
     725         Assert.notNull(registrar, "PropertyEditorRegistrar must not be null");
     726         this.propertyEditorRegistrars.add(registrar);
     727     }
     728 
     729     /**
     730      * Return the set of PropertyEditorRegistrars.
     731      */
     732     public Set<PropertyEditorRegistrar> getPropertyEditorRegistrars() {
     733         return this.propertyEditorRegistrars;
     734     }
     735 
     736     @Override
     737     public void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass) {
     738         Assert.notNull(requiredType, "Required type must not be null");
     739         Assert.isAssignable(PropertyEditor.class, propertyEditorClass);
     740         this.customEditors.put(requiredType, propertyEditorClass);
     741     }
     742 
     743     @Override
     744     public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) {
     745         registerCustomEditors(registry);
     746     }
     747 
     748     /**
     749      * Return the map of custom editors, with Classes as keys and PropertyEditor classes as values.
     750      */
     751     public Map<Class<?>, Class<? extends PropertyEditor>> getCustomEditors() {
     752         return this.customEditors;
     753     }
     754 
     755     @Override
     756     public void setTypeConverter(TypeConverter typeConverter) {
     757         this.typeConverter = typeConverter;
     758     }
     759 
     760     /**
     761      * Return the custom TypeConverter to use, if any.
     762      *
     763      * @return the custom TypeConverter, or {@code null} if none specified
     764      */
     765     protected TypeConverter getCustomTypeConverter() {
     766         return this.typeConverter;
     767     }
     768 
     769     @Override
     770     public TypeConverter getTypeConverter() {
     771         TypeConverter customConverter = getCustomTypeConverter();
     772         if (customConverter != null) {
     773             return customConverter;
     774         } else {
     775             // Build default TypeConverter, registering custom editors.
     776             SimpleTypeConverter typeConverter = new SimpleTypeConverter();
     777             typeConverter.setConversionService(getConversionService());
     778             registerCustomEditors(typeConverter);
     779             return typeConverter;
     780         }
     781     }
     782 
     783     @Override
     784     public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
     785         Assert.notNull(valueResolver, "StringValueResolver must not be null");
     786         this.embeddedValueResolvers.add(valueResolver);
     787     }
     788 
     789     @Override
     790     public String resolveEmbeddedValue(String value) {
     791         String result = value;
     792         for (StringValueResolver resolver : this.embeddedValueResolvers) {
     793             if (result == null) {
     794                 return null;
     795             }
     796             result = resolver.resolveStringValue(result);
     797         }
     798         return result;
     799     }
     800 
     801     @Override
     802     public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
     803         Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
     804         this.beanPostProcessors.remove(beanPostProcessor);
     805         this.beanPostProcessors.add(beanPostProcessor);
     806         if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
     807             this.hasInstantiationAwareBeanPostProcessors = true;
     808         }
     809         if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
     810             this.hasDestructionAwareBeanPostProcessors = true;
     811         }
     812     }
     813 
     814     @Override
     815     public int getBeanPostProcessorCount() {
     816         return this.beanPostProcessors.size();
     817     }
     818 
     819     /**
     820      * Return the list of BeanPostProcessors that will get applied
     821      * to beans created with this factory.
     822      */
     823     public List<BeanPostProcessor> getBeanPostProcessors() {
     824         return this.beanPostProcessors;
     825     }
     826 
     827     /**
     828      * Return whether this factory holds a InstantiationAwareBeanPostProcessor
     829      * that will get applied to singleton beans on shutdown.
     830      *
     831      * @see #addBeanPostProcessor
     832      * @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor
     833      */
     834     protected boolean hasInstantiationAwareBeanPostProcessors() {
     835         return this.hasInstantiationAwareBeanPostProcessors;
     836     }
     837 
     838     /**
     839      * Return whether this factory holds a DestructionAwareBeanPostProcessor
     840      * that will get applied to singleton beans on shutdown.
     841      *
     842      * @see #addBeanPostProcessor
     843      * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor
     844      */
     845     protected boolean hasDestructionAwareBeanPostProcessors() {
     846         return this.hasDestructionAwareBeanPostProcessors;
     847     }
     848 
     849     @Override
     850     public void registerScope(String scopeName, Scope scope) {
     851         Assert.notNull(scopeName, "Scope identifier must not be null");
     852         Assert.notNull(scope, "Scope must not be null");
     853         if (SCOPE_SINGLETON.equals(scopeName) || SCOPE_PROTOTYPE.equals(scopeName)) {
     854             throw new IllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'");
     855         }
     856         Scope previous = this.scopes.put(scopeName, scope);
     857         if (previous != null && previous != scope) {
     858             if (logger.isInfoEnabled()) {
     859                 logger.info("Replacing scope '" + scopeName + "' from [" + previous + "] to [" + scope + "]");
     860             }
     861         } else {
     862             if (logger.isDebugEnabled()) {
     863                 logger.debug("Registering scope '" + scopeName + "' with implementation [" + scope + "]");
     864             }
     865         }
     866     }
     867 
     868     @Override
     869     public String[] getRegisteredScopeNames() {
     870         return StringUtils.toStringArray(this.scopes.keySet());
     871     }
     872 
     873     @Override
     874     public Scope getRegisteredScope(String scopeName) {
     875         Assert.notNull(scopeName, "Scope identifier must not be null");
     876         return this.scopes.get(scopeName);
     877     }
     878 
     879     /**
     880      * Set the security context provider for this bean factory. If a security manager
     881      * is set, interaction with the user code will be executed using the privileged
     882      * of the provided security context.
     883      */
     884     public void setSecurityContextProvider(SecurityContextProvider securityProvider) {
     885         this.securityContextProvider = securityProvider;
     886     }
     887 
     888     /**
     889      * Delegate the creation of the access control context to the
     890      * {@link #setSecurityContextProvider SecurityContextProvider}.
     891      */
     892     @Override
     893     public AccessControlContext getAccessControlContext() {
     894         return (this.securityContextProvider != null ?
     895                 this.securityContextProvider.getAccessControlContext() :
     896                 AccessController.getContext());
     897     }
     898 
     899     @Override
     900     public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
     901         Assert.notNull(otherFactory, "BeanFactory must not be null");
     902         setBeanClassLoader(otherFactory.getBeanClassLoader());
     903         setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());
     904         setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());
     905         if (otherFactory instanceof AbstractBeanFactory) {
     906             AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory;
     907             this.customEditors.putAll(otherAbstractFactory.customEditors);
     908             this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars);
     909             this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors);
     910             this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors ||
     911                     otherAbstractFactory.hasInstantiationAwareBeanPostProcessors;
     912             this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors ||
     913                     otherAbstractFactory.hasDestructionAwareBeanPostProcessors;
     914             this.scopes.putAll(otherAbstractFactory.scopes);
     915             this.securityContextProvider = otherAbstractFactory.securityContextProvider;
     916         } else {
     917             setTypeConverter(otherFactory.getTypeConverter());
     918         }
     919     }
     920 
     921     /**
     922      * Return a 'merged' BeanDefinition for the given bean name,
     923      * merging a child bean definition with its parent if necessary.
     924      * <p>This {@code getMergedBeanDefinition} considers bean definition
     925      * in ancestors as well.
     926      *
     927      * @param name the name of the bean to retrieve the merged definition for
     928      *             (may be an alias)
     929      * @return a (potentially merged) RootBeanDefinition for the given bean
     930      * @throws NoSuchBeanDefinitionException if there is no bean with the given name
     931      * @throws BeanDefinitionStoreException  in case of an invalid bean definition
     932      */
     933     @Override
     934     public BeanDefinition getMergedBeanDefinition(String name) throws BeansException {
     935         String beanName = transformedBeanName(name);
     936 
     937         // Efficiently check whether bean definition exists in this factory.
     938         if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
     939             return ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(beanName);
     940         }
     941         // Resolve merged bean definition locally.
     942         return getMergedLocalBeanDefinition(beanName);
     943     }
     944 
     945     @Override
     946     public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {
     947         String beanName = transformedBeanName(name);
     948 
     949         Object beanInstance = getSingleton(beanName, false);
     950         if (beanInstance != null) {
     951             return (beanInstance instanceof FactoryBean);
     952         } else if (containsSingleton(beanName)) {
     953             // 可能这个bean不允许被创建(abstract的bean)?
     954             // null instance registered
     955             return false;
     956         }
     957 
     958         // No singleton instance found -> check bean definition.
     959         if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
     960             // No bean definition found in this factory -> delegate to parent.
     961             // 本BF没有就找父类的
     962             return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);
     963         }
     964 
     965         return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));
     966     }
     967 
     968     @Override
     969     public boolean isActuallyInCreation(String beanName) {
     970         return (isSingletonCurrentlyInCreation(beanName) || isPrototypeCurrentlyInCreation(beanName));
     971     }
     972 
     973     /**
     974      * Return whether the specified prototype bean is currently in creation
     975      * (within the current thread).
     976      *
     977      * @param beanName the name of the bean
     978      */
     979     protected boolean isPrototypeCurrentlyInCreation(String beanName) {
     980         Object curVal = this.prototypesCurrentlyInCreation.get();
     981         return (curVal != null &&
     982                 (curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
     983     }
     984 
     985     /**
     986      * Callback before prototype creation.
     987      * 将正在创建的额原型bean放到threadlocal中,1个原型bean的类在1个线程中只能有1个正在创建的实例
     988      * <p>The default implementation register the prototype as currently in creation.
     989      *
     990      * @param beanName the name of the prototype about to be created
     991      * @see #isPrototypeCurrentlyInCreation
     992      */
     993     @SuppressWarnings("unchecked")
     994     protected void beforePrototypeCreation(String beanName) {
     995         Object curVal = this.prototypesCurrentlyInCreation.get();
     996         if (curVal == null) {
     997             this.prototypesCurrentlyInCreation.set(beanName);
     998         } else if (curVal instanceof String) {
     999             Set<String> beanNameSet = new HashSet<String>(2);
    1000             beanNameSet.add((String) curVal);
    1001             beanNameSet.add(beanName);
    1002             this.prototypesCurrentlyInCreation.set(beanNameSet);
    1003         } else {
    1004             Set<String> beanNameSet = (Set<String>) curVal;
    1005             beanNameSet.add(beanName);
    1006         }
    1007     }
    1008 
    1009     /**
    1010      * Callback after prototype creation.
    1011      * 将之前线程变量中存着的正在创建的原型bean移除,因为已经创建完毕
    1012      * <p>The default implementation marks the prototype as not in creation anymore.
    1013      *
    1014      * @param beanName the name of the prototype that has been created
    1015      * @see #isPrototypeCurrentlyInCreation
    1016      */
    1017     @SuppressWarnings("unchecked")
    1018     protected void afterPrototypeCreation(String beanName) {
    1019         Object curVal = this.prototypesCurrentlyInCreation.get();
    1020         if (curVal instanceof String) {
    1021             this.prototypesCurrentlyInCreation.remove();
    1022         } else if (curVal instanceof Set) {
    1023             Set<String> beanNameSet = (Set<String>) curVal;
    1024             beanNameSet.remove(beanName);
    1025             if (beanNameSet.isEmpty()) {
    1026                 this.prototypesCurrentlyInCreation.remove();
    1027             }
    1028         }
    1029     }
    1030 
    1031     @Override
    1032     public void destroyBean(String beanName, Object beanInstance) {
    1033         destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName));
    1034     }
    1035 
    1036     /**
    1037      * Destroy the given bean instance (usually a prototype instance
    1038      * obtained from this factory) according to the given bean definition.
    1039      *
    1040      * @param beanName     the name of the bean definition
    1041      * @param beanInstance the bean instance to destroy
    1042      * @param mbd          the merged bean definition
    1043      */
    1044     protected void destroyBean(String beanName, Object beanInstance, RootBeanDefinition mbd) {
    1045         new DisposableBeanAdapter(beanInstance, beanName, mbd, getBeanPostProcessors(), getAccessControlContext()).destroy();
    1046     }
    1047 
    1048     @Override
    1049     public void destroyScopedBean(String beanName) {
    1050         RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
    1051         if (mbd.isSingleton() || mbd.isPrototype()) {
    1052             throw new IllegalArgumentException(
    1053                     "Bean name '" + beanName + "' does not correspond to an object in a mutable scope");
    1054         }
    1055         String scopeName = mbd.getScope();
    1056         Scope scope = this.scopes.get(scopeName);
    1057         if (scope == null) {
    1058             throw new IllegalStateException("No Scope SPI registered for scope '" + scopeName + "'");
    1059         }
    1060         Object bean = scope.remove(beanName);
    1061         if (bean != null) {
    1062             destroyBean(beanName, bean, mbd);
    1063         }
    1064     }
    1065 
    1066 
    1067     //---------------------------------------------------------------------
    1068     // Implementation methods
    1069     //---------------------------------------------------------------------
    1070 
    1071     /**
    1072      * Return the bean name, stripping out the factory dereference prefix if necessary,
    1073      * and resolving aliases to canonical names.
    1074      * 去掉&前缀,并且把alias->真正的beanname
    1075      *
    1076      * @param name the user-specified name
    1077      * @return the transformed bean name
    1078      */
    1079     protected String transformedBeanName(String name) {
    1080         return canonicalName(BeanFactoryUtils.transformedBeanName(name));
    1081     }
    1082 
    1083     /**
    1084      * Determine the original bean name, resolving locally defined aliases to canonical names.
    1085      *
    1086      * @param name the user-specified name
    1087      * @return the original bean name
    1088      */
    1089     protected String originalBeanName(String name) {
    1090         String beanName = transformedBeanName(name);
    1091         if (name.startsWith(FACTORY_BEAN_PREFIX)) {
    1092             beanName = FACTORY_BEAN_PREFIX + beanName;
    1093         }
    1094         return beanName;
    1095     }
    1096 
    1097     /**
    1098      * Initialize the given BeanWrapper with the custom editors registered
    1099      * with this factory. To be called for BeanWrappers that will create
    1100      * and populate bean instances.
    1101      * <p>The default implementation delegates to {@link #registerCustomEditors}.
    1102      * Can be overridden in subclasses.
    1103      *
    1104      * @param bw the BeanWrapper to initialize
    1105      */
    1106     protected void initBeanWrapper(BeanWrapper bw) {
    1107         bw.setConversionService(getConversionService());
    1108         registerCustomEditors(bw);
    1109     }
    1110 
    1111     /**
    1112      * Initialize the given PropertyEditorRegistry with the custom editors
    1113      * that have been registered with this BeanFactory.
    1114      * <p>To be called for BeanWrappers that will create and populate bean
    1115      * instances, and for SimpleTypeConverter used for constructor argument
    1116      * and factory method type conversion.
    1117      *
    1118      * @param registry the PropertyEditorRegistry to initialize
    1119      */
    1120     protected void registerCustomEditors(PropertyEditorRegistry registry) {
    1121         PropertyEditorRegistrySupport registrySupport =
    1122                 (registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);
    1123         if (registrySupport != null) {
    1124             registrySupport.useConfigValueEditors();
    1125         }
    1126         if (!this.propertyEditorRegistrars.isEmpty()) {
    1127             for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
    1128                 try {
    1129                     registrar.registerCustomEditors(registry);
    1130                 } catch (BeanCreationException ex) {
    1131                     Throwable rootCause = ex.getMostSpecificCause();
    1132                     if (rootCause instanceof BeanCurrentlyInCreationException) {
    1133                         BeanCreationException bce = (BeanCreationException) rootCause;
    1134                         if (isCurrentlyInCreation(bce.getBeanName())) {
    1135                             if (logger.isDebugEnabled()) {
    1136                                 logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
    1137                                         "] failed because it tried to obtain currently created bean '" +
    1138                                         ex.getBeanName() + "': " + ex.getMessage());
    1139                             }
    1140                             onSuppressedException(ex);
    1141                             continue;
    1142                         }
    1143                     }
    1144                     throw ex;
    1145                 }
    1146             }
    1147         }
    1148         if (!this.customEditors.isEmpty()) {
    1149             for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : this.customEditors.entrySet()) {
    1150                 Class<?> requiredType = entry.getKey();
    1151                 Class<? extends PropertyEditor> editorClass = entry.getValue();
    1152                 registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass));
    1153             }
    1154         }
    1155     }
    1156 
    1157 
    1158     /**
    1159      * Return a merged RootBeanDefinition, traversing the parent bean definition
    1160      * if the specified bean corresponds to a child bean definition.
    1161      * 有缓存直接缓存取,没有的话就合并自己的和父类的.
    1162      *
    1163      * @param beanName the name of the bean to retrieve the merged definition for
    1164      * @return a (potentially merged) RootBeanDefinition for the given bean
    1165      * @throws NoSuchBeanDefinitionException if there is no bean with the given name
    1166      * @throws BeanDefinitionStoreException  in case of an invalid bean definition
    1167      */
    1168     protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
    1169         // Quick check on the concurrent map first, with minimal locking.
    1170         RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
    1171         if (mbd != null) {
    1172             return mbd;
    1173         }
    1174         return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
    1175     }
    1176 
    1177     /**
    1178      * Return a RootBeanDefinition for the given top-level bean, by merging with
    1179      * the parent if the given bean's definition is a child bean definition.
    1180      *
    1181      * @param beanName the name of the bean definition
    1182      * @param bd       the original bean definition (Root/ChildBeanDefinition)
    1183      * @return a (potentially merged) RootBeanDefinition for the given bean
    1184      * @throws BeanDefinitionStoreException in case of an invalid bean definition
    1185      */
    1186     protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
    1187             throws BeanDefinitionStoreException {
    1188 
    1189         return getMergedBeanDefinition(beanName, bd, null);
    1190     }
    1191 
    1192     /**
    1193      * Return a RootBeanDefinition for the given bean, by merging with the
    1194      * parent if the given bean's definition is a child bean definition.
    1195      *
    1196      * @param beanName     the name of the bean definition
    1197      * @param bd           the original bean definition (Root/ChildBeanDefinition)
    1198      * @param containingBd the containing bean definition in case of inner bean,
    1199      *                     or {@code null} in case of a top-level bean
    1200      * @return a (potentially merged) RootBeanDefinition for the given bean
    1201      * @throws BeanDefinitionStoreException in case of an invalid bean definition
    1202      */
    1203     protected RootBeanDefinition getMergedBeanDefinition(
    1204             String beanName, BeanDefinition bd, BeanDefinition containingBd)
    1205             throws BeanDefinitionStoreException {
    1206 
    1207         synchronized (this.mergedBeanDefinitions) {
    1208             RootBeanDefinition mbd = null;
    1209 
    1210             // Check with full lock now in order to enforce the same merged instance.
    1211             if (containingBd == null) {
    1212                 mbd = this.mergedBeanDefinitions.get(beanName);
    1213             }
    1214 
    1215             if (mbd == null) {
    1216                 if (bd.getParentName() == null) {
    1217                     // Use copy of given root bean definition.
    1218                     if (bd instanceof RootBeanDefinition) {
    1219                         mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
    1220                     } else {
    1221                         mbd = new RootBeanDefinition(bd);
    1222                     }
    1223                 } else {
    1224                     // Child bean definition: needs to be merged with parent.
    1225                     BeanDefinition pbd;
    1226                     try {
    1227                         String parentBeanName = transformedBeanName(bd.getParentName());
    1228                         if (!beanName.equals(parentBeanName)) {
    1229                             pbd = getMergedBeanDefinition(parentBeanName);
    1230                         } else {
    1231                             if (getParentBeanFactory() instanceof ConfigurableBeanFactory) {
    1232                                 pbd = ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(parentBeanName);
    1233                             } else {
    1234                                 throw new NoSuchBeanDefinitionException(bd.getParentName(),
    1235                                         "Parent name '" + bd.getParentName() + "' is equal to bean name '" + beanName +
    1236                                                 "': cannot be resolved without an AbstractBeanFactory parent");
    1237                             }
    1238                         }
    1239                     } catch (NoSuchBeanDefinitionException ex) {
    1240                         throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
    1241                                 "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
    1242                     }
    1243                     // Deep copy with overridden values.
    1244                     mbd = new RootBeanDefinition(pbd);
    1245                     mbd.overrideFrom(bd);
    1246                 }
    1247 
    1248                 // Set default singleton scope, if not configured before.
    1249                 if (!StringUtils.hasLength(mbd.getScope())) {
    1250                     mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
    1251                 }
    1252 
    1253                 // A bean contained in a non-singleton bean cannot be a singleton itself.
    1254                 // Let's correct this on the fly here, since this might be the result of
    1255                 // parent-child merging for the outer bean, in which case the original inner bean
    1256                 // definition will not have inherited the merged outer bean's singleton status.
    1257                 if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
    1258                     mbd.setScope(containingBd.getScope());
    1259                 }
    1260 
    1261                 // Only cache the merged bean definition if we're already about to create an
    1262                 // instance of the bean, or at least have already created an instance before.
    1263                 if (containingBd == null && isCacheBeanMetadata() && isBeanEligibleForMetadataCaching(beanName)) {
    1264                     this.mergedBeanDefinitions.put(beanName, mbd);
    1265                 }
    1266             }
    1267 
    1268             return mbd;
    1269         }
    1270     }
    1271 
    1272     /**
    1273      * Check the given merged bean definition,
    1274      * potentially throwing validation exceptions.
    1275      *
    1276      * @param mbd      the merged bean definition to check
    1277      * @param beanName the name of the bean
    1278      * @param args     the arguments for bean creation, if any
    1279      * @throws BeanDefinitionStoreException in case of validation failure
    1280      */
    1281     protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, Object[] args)
    1282             throws BeanDefinitionStoreException {
    1283 
    1284         if (mbd.isAbstract()) {
    1285             throw new BeanIsAbstractException(beanName);
    1286         }
    1287     }
    1288 
    1289     /**
    1290      * Remove the merged bean definition for the specified bean,
    1291      * recreating it on next access.
    1292      *
    1293      * @param beanName the bean name to clear the merged definition for
    1294      */
    1295     protected void clearMergedBeanDefinition(String beanName) {
    1296         this.mergedBeanDefinitions.remove(beanName);
    1297     }
    1298 
    1299     /**
    1300      * Resolve the bean class for the specified bean definition,
    1301      * resolving a bean class name into a Class reference (if necessary)
    1302      * and storing the resolved Class in the bean definition for further use.
    1303      *
    1304      * @param mbd          the merged bean definition to determine the class for
    1305      * @param beanName     the name of the bean (for error handling purposes)
    1306      * @param typesToMatch the types to match in case of internal type matching purposes
    1307      *                     (also signals that the returned {@code Class} will never be exposed to application code)
    1308      * @return the resolved bean class (or {@code null} if none)
    1309      * @throws CannotLoadBeanClassException if we failed to load the class
    1310      */
    1311     protected Class<?> resolveBeanClass(final RootBeanDefinition mbd, String beanName, final Class<?>... typesToMatch)
    1312             throws CannotLoadBeanClassException {
    1313         try {
    1314             if (mbd.hasBeanClass()) {
    1315                 return mbd.getBeanClass();
    1316             }
    1317             if (System.getSecurityManager() != null) {
    1318                 return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() {
    1319                     @Override
    1320                     public Class<?> run() throws Exception {
    1321                         return doResolveBeanClass(mbd, typesToMatch);
    1322                     }
    1323                 }, getAccessControlContext());
    1324             } else {
    1325                 return doResolveBeanClass(mbd, typesToMatch);
    1326             }
    1327         } catch (PrivilegedActionException pae) {
    1328             ClassNotFoundException ex = (ClassNotFoundException) pae.getException();
    1329             throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
    1330         } catch (ClassNotFoundException ex) {
    1331             throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
    1332         } catch (LinkageError err) {
    1333             throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err);
    1334         }
    1335     }
    1336 
    1337     private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch) throws ClassNotFoundException {
    1338         if (!ObjectUtils.isEmpty(typesToMatch)) {
    1339             ClassLoader tempClassLoader = getTempClassLoader();
    1340             if (tempClassLoader != null) {
    1341                 if (tempClassLoader instanceof DecoratingClassLoader) {
    1342                     DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader;
    1343                     for (Class<?> typeToMatch : typesToMatch) {
    1344                         dcl.excludeClass(typeToMatch.getName());
    1345                     }
    1346                 }
    1347                 String className = mbd.getBeanClassName();
    1348                 return (className != null ? ClassUtils.forName(className, tempClassLoader) : null);
    1349             }
    1350         }
    1351         return mbd.resolveBeanClass(getBeanClassLoader());
    1352     }
    1353 
    1354     /**
    1355      * Evaluate the given String as contained in a bean definition,
    1356      * potentially resolving it as an expression.
    1357      *
    1358      * @param value          the value to check
    1359      * @param beanDefinition the bean definition that the value comes from
    1360      * @return the resolved value
    1361      * @see #setBeanExpressionResolver
    1362      */
    1363     protected Object evaluateBeanDefinitionString(String value, BeanDefinition beanDefinition) {
    1364         if (this.beanExpressionResolver == null) {
    1365             return value;
    1366         }
    1367         Scope scope = (beanDefinition != null ? getRegisteredScope(beanDefinition.getScope()) : null);
    1368         return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope));
    1369     }
    1370 
    1371 
    1372     /**
    1373      * Predict the eventual bean type (of the processed bean instance) for the
    1374      * specified bean. Called by {@link #getType} and {@link #isTypeMatch}.
    1375      * Does not need to handle FactoryBeans specifically, since it is only
    1376      * supposed to operate on the raw bean type.
    1377      * <p>This implementation is simplistic in that it is not able to
    1378      * handle factory methods and InstantiationAwareBeanPostProcessors.
    1379      * It only predicts the bean type correctly for a standard bean.
    1380      * To be overridden in subclasses, applying more sophisticated type detection.
    1381      *
    1382      * @param beanName     the name of the bean
    1383      * @param mbd          the merged bean definition to determine the type for
    1384      * @param typesToMatch the types to match in case of internal type matching purposes
    1385      *                     (also signals that the returned {@code Class} will never be exposed to application code)
    1386      * @return the type of the bean, or {@code null} if not predictable
    1387      */
    1388     protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
    1389         if (mbd.getFactoryMethodName() != null) {
    1390             return null;
    1391         }
    1392         return resolveBeanClass(mbd, beanName, typesToMatch);
    1393     }
    1394 
    1395     /**
    1396      * Check whether the given bean is defined as a {@link FactoryBean}.
    1397      *
    1398      * @param beanName the name of the bean
    1399      * @param mbd      the corresponding bean definition
    1400      */
    1401     protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) {
    1402         Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class);
    1403         return (beanType != null && FactoryBean.class.isAssignableFrom(beanType));
    1404     }
    1405 
    1406     /**
    1407      * Determine the bean type for the given FactoryBean definition, as far as possible.
    1408      * Only called if there is no singleton instance registered for the target bean already.
    1409      * <p>The default implementation creates the FactoryBean via {@code getBean}
    1410      * to call its {@code getObjectType} method. Subclasses are encouraged to optimize
    1411      * this, typically by just instantiating the FactoryBean but not populating it yet,
    1412      * trying whether its {@code getObjectType} method already returns a type.
    1413      * If no type found, a full FactoryBean creation as performed by this implementation
    1414      * should be used as fallback.
    1415      *
    1416      * @param beanName the name of the bean
    1417      * @param mbd      the merged bean definition for the bean
    1418      * @return the type for the bean if determinable, or {@code null} else
    1419      * @see org.springframework.beans.factory.FactoryBean#getObjectType()
    1420      * @see #getBean(String)
    1421      */
    1422     protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
    1423         if (!mbd.isSingleton()) {
    1424             return null;
    1425         }
    1426         try {
    1427             FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
    1428             return getTypeForFactoryBean(factoryBean);
    1429         } catch (BeanCreationException ex) {
    1430             if (ex instanceof BeanCurrentlyInCreationException) {
    1431                 if (logger.isDebugEnabled()) {
    1432                     logger.debug("Bean currently in creation on FactoryBean type check: " + ex);
    1433                 }
    1434             } else {
    1435                 if (logger.isWarnEnabled()) {
    1436                     logger.warn("Bean creation exception on FactoryBean type check: " + ex);
    1437                 }
    1438             }
    1439             onSuppressedException(ex);
    1440             return null;
    1441         }
    1442     }
    1443 
    1444     /**
    1445      * Mark the specified bean as already created (or about to be created).
    1446      * <p>This allows the bean factory to optimize its caching for repeated
    1447      * creation of the specified bean.
    1448      *
    1449      * @param beanName the name of the bean
    1450      */
    1451     protected void markBeanAsCreated(String beanName) {
    1452         if (!this.alreadyCreated.contains(beanName)) {
    1453             this.alreadyCreated.add(beanName);
    1454         }
    1455     }
    1456 
    1457     /**
    1458      * Perform appropriate cleanup of cached metadata after bean creation failed.
    1459      *
    1460      * @param beanName the name of the bean
    1461      */
    1462     protected void cleanupAfterBeanCreationFailure(String beanName) {
    1463         this.alreadyCreated.remove(beanName);
    1464     }
    1465 
    1466     /**
    1467      * Determine whether the specified bean is eligible for having
    1468      * its bean definition metadata cached.
    1469      *
    1470      * @param beanName the name of the bean
    1471      * @return {@code true} if the bean's metadata may be cached
    1472      * at this point already
    1473      */
    1474     protected boolean isBeanEligibleForMetadataCaching(String beanName) {
    1475         return this.alreadyCreated.contains(beanName);
    1476     }
    1477 
    1478     /**
    1479      * Remove the singleton instance (if any) for the given bean name,
    1480      * but only if it hasn't been used for other purposes than type checking.
    1481      *
    1482      * @param beanName the name of the bean
    1483      * @return {@code true} if actually removed, {@code false} otherwise
    1484      */
    1485     protected boolean removeSingletonIfCreatedForTypeCheckOnly(String beanName) {
    1486         if (!this.alreadyCreated.contains(beanName)) {
    1487             removeSingleton(beanName);
    1488             return true;
    1489         } else {
    1490             return false;
    1491         }
    1492     }
    1493 
    1494     /**
    1495      * Get the object for the given bean instance, either the bean
    1496      * instance itself or its created object in case of a FactoryBean.
    1497      *
    1498      * @param beanInstance the shared bean instance
    1499      * @param name         name that may include factory dereference prefix
    1500      * @param beanName     the canonical bean name
    1501      * @param mbd          the merged bean definition
    1502      * @return the object to expose for the bean
    1503      */
    1504     protected Object getObjectForBeanInstance(
    1505             Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {
    1506 
    1507         // Don't let calling code try to dereference the factory if the bean isn't a factory.
    1508         // & 开头.但是这个bean却又不是FactoryBean.说明有问题. &都应该是factorybean
    1509         if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
    1510             throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
    1511         }
    1512 
    1513         // Now we have the bean instance, which may be a normal bean or a FactoryBean.
    1514         // If it's a FactoryBean, we use it to create a bean instance, unless the
    1515         // caller actually wants a reference to the factory.
    1516         // 不是FactoryBean直接返回这个bean,&开头的话也直接返回这个bean.
    1517         if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
    1518             return beanInstance;
    1519         }
    1520 
    1521         Object object = null;
    1522         if (mbd == null) {
    1523             // 说明这个bean是需要从FactoryBean的getObject方法中返回的.
    1524             object = getCachedObjectForFactoryBean(beanName);
    1525         }
    1526         if (object == null) { // 没有cache.需要生成的情况
    1527             // Return bean instance from factory.
    1528             FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
    1529             // Caches object obtained from FactoryBean if it is a singleton.
    1530             if (mbd == null && containsBeanDefinition(beanName)) {
    1531                 mbd = getMergedLocalBeanDefinition(beanName); // 合并bean的定义
    1532             }
    1533             boolean synthetic = (mbd != null && mbd.isSynthetic());
    1534             object = getObjectFromFactoryBean(factory, beanName, !synthetic); // 不是合成的bean的定义的话这个bean从工厂中生成需要调用postProcessObjectFromFactoryBean方法对bean进行加工,我觉得是因为父类中的这些后置处理bean当前工厂里没有
    1535         }
    1536         return object;
    1537     }
    1538 
    1539     /**
    1540      * Determine whether the given bean name is already in use within this factory,
    1541      * i.e. whether there is a local bean or alias registered under this name or
    1542      * an inner bean created with this name.
    1543      *
    1544      * @param beanName the name to check
    1545      */
    1546     public boolean isBeanNameInUse(String beanName) {
    1547         return isAlias(beanName) || containsLocalBean(beanName) || hasDependentBean(beanName);
    1548     }
    1549 
    1550     /**
    1551      * Determine whether the given bean requires destruction on shutdown.
    1552      * <p>The default implementation checks the DisposableBean interface as well as
    1553      * a specified destroy method and registered DestructionAwareBeanPostProcessors.
    1554      *
    1555      * @param bean the bean instance to check
    1556      * @param mbd  the corresponding bean definition
    1557      * @see org.springframework.beans.factory.DisposableBean
    1558      * @see AbstractBeanDefinition#getDestroyMethodName()
    1559      * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor
    1560      */
    1561     protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
    1562         return (bean != null &&
    1563                 (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || hasDestructionAwareBeanPostProcessors()));
    1564     }
    1565 
    1566     /**
    1567      * Add the given bean to the list of disposable beans in this factory,
    1568      * registering its DisposableBean interface and/or the given destroy method
    1569      * to be called on factory shutdown (if applicable). Only applies to singletons.
    1570      *
    1571      * @param beanName the name of the bean
    1572      * @param bean     the bean instance
    1573      * @param mbd      the bean definition for the bean
    1574      * @see RootBeanDefinition#isSingleton
    1575      * @see RootBeanDefinition#getDependsOn
    1576      * @see #registerDisposableBean
    1577      * @see #registerDependentBean
    1578      */
    1579     protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
    1580         AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
    1581         if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
    1582             if (mbd.isSingleton()) {
    1583                 // Register a DisposableBean implementation that performs all destruction
    1584                 // work for the given bean: DestructionAwareBeanPostProcessors,
    1585                 // DisposableBean interface, custom destroy method.
    1586                 registerDisposableBean(beanName,
    1587                         new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
    1588             } else {
    1589                 // A bean with a custom scope...
    1590                 Scope scope = this.scopes.get(mbd.getScope());
    1591                 if (scope == null) {
    1592                     throw new IllegalStateException("No Scope registered for scope '" + mbd.getScope() + "'");
    1593                 }
    1594                 scope.registerDestructionCallback(beanName,
    1595                         new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
    1596             }
    1597         }
    1598     }
    1599 
    1600 
    1601     //---------------------------------------------------------------------
    1602     // Abstract methods to be implemented by subclasses
    1603     //---------------------------------------------------------------------
    1604 
    1605     /**
    1606      * Check if this bean factory contains a bean definition with the given name.
    1607      * Does not consider any hierarchy this factory may participate in.
    1608      * Invoked by {@code containsBean} when no cached singleton instance is found.
    1609      * <p>Depending on the nature of the concrete bean factory implementation,
    1610      * this operation might be expensive (for example, because of directory lookups
    1611      * in external registries). However, for listable bean factories, this usually
    1612      * just amounts to a local hash lookup: The operation is therefore part of the
    1613      * public interface there. The same implementation can serve for both this
    1614      * template method and the public interface method in that case.
    1615      * 当前这个BF不算父类的.是否包含了给定的beanname对应的Definition
    1616      *
    1617      * @param beanName the name of the bean to look for
    1618      * @return if this bean factory contains a bean definition with the given name
    1619      * @see #containsBean
    1620      * @see org.springframework.beans.factory.ListableBeanFactory#containsBeanDefinition
    1621      */
    1622     protected abstract boolean containsBeanDefinition(String beanName);
    1623 
    1624     /**
    1625      * Return the bean definition for the given bean name.
    1626      * Subclasses should normally implement caching, as this method is invoked
    1627      * by this class every time bean definition metadata is needed.
    1628      * <p>Depending on the nature of the concrete bean factory implementation,
    1629      * this operation might be expensive (for example, because of directory lookups
    1630      * in external registries). However, for listable bean factories, this usually
    1631      * just amounts to a local hash lookup: The operation is therefore part of the
    1632      * public interface there. The same implementation can serve for both this
    1633      * template method and the public interface method in that case.
    1634      * 根据beanname获取BeanDefinition,子类实现,可以用缓存
    1635      *
    1636      * @param beanName the name of the bean to find a definition for
    1637      * @return the BeanDefinition for this prototype name (never {@code null})
    1638      * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException if the bean definition cannot be resolved
    1639      * @throws BeansException                                                  in case of errors
    1640      * @see RootBeanDefinition
    1641      * @see ChildBeanDefinition
    1642      * @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory#getBeanDefinition
    1643      */
    1644     protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;
    1645 
    1646     /**
    1647      * Create a bean instance for the given merged bean definition (and arguments).
    1648      * The bean definition will already have been merged with the parent definition
    1649      * in case of a child definition.
    1650      * <p>All bean retrieval methods delegate to this method for actual bean creation.
    1651      *
    1652      * @param beanName the name of the bean
    1653      * @param mbd      the merged bean definition for the bean
    1654      * @param args     explicit arguments to use for constructor or factory method invocation
    1655      * @return a new instance of the bean
    1656      * @throws BeanCreationException if the bean could not be created
    1657      */
    1658     protected abstract Object createBean(String beanName, RootBeanDefinition mbd, Object[] args)
    1659             throws BeanCreationException;
    1660 
    1661 }
    View Code

    一些方法加了注释,还有很多方法和其中的ifelse不明白为什么要这么写...

    后续的一些逻辑要做实验才会明白了....

  • 相关阅读:
    一致性 hash 算法( consistent hashing )a
    wcf 推送 与 广播
    TFS 自动同步Server 端文件的批处理命令
    PHP面向对象
    H5缓存机制浅析-移动端Web加载性能优化【干货】
    100+ 超全的web开发工具和资源
    从零开始搭建论坛(一):Web服务器与Web框架
    JQuery:选择器
    JQuery:事件
    JQuery:DOM操作
  • 原文地址:https://www.cnblogs.com/abcwt112/p/7574915.html
Copyright © 2011-2022 走看看