spring-beans深入源码之获取Bean的过程解析

上一篇博文大致说完了Bean Definition 从xml文件的载入过程,真正需要bean的时候还是要从BeanFactory get获取的。接下来看一下bean的get过程。
查看test方法

TestBean bean = (TestBean) this.beanFactory.getBean("childWithList");

这里的this.beanFactory 是上面setUp方法中创建的

this.beanFactory = new DefaultListableBeanFactory();

可以知道 setUp方法装配了bean definition到了BeanFactory中,最后你需要的用到bean的时候还是需要从BeanFactory中获取。
继续debug进入到

@Override
public Object getBean(String name) throws BeansException {
      return doGetBean(name, null, null, false);
}

继续进入到获取bean的主要方法

spring-beans深入源码之获取Bean的过程解析_第1张图片
bean获取的主要方法

第一行 final String beanName = transformedBeanName(name); 是对你传入的bean的name的转换,代码内部用到了 BeanFactoryUtils.transformedBeanName(name)方法,该方法主要是去掉以 String FACTORY_BEAN_PREFIX = "&";开头的bean的name,截取&后面的部分,最后会查看 private final Map aliasMap = new ConcurrentHashMap(16);别名map中是否已经存在这个bean name 存在则沿用以前的bean name。接着继续获取bean 这里有一段代码注释 // Eagerly check singleton cache for manually registered singletons. 大致意思就是先从已经注册到BeanFactory的单例的map里面去获取这个bean name的单例bean, Object sharedInstance = getSingleton(beanName);.主要的方法代码:

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
            synchronized (this.singletonObjects) {
                singletonObject = this.earlySingletonObjects.get(beanName);
                if (singletonObject == null && allowEarlyReference) {
                    ObjectFactory singletonFactory = this.singletonFactories.get(beanName);
                    if (singletonFactory != null) {
                        singletonObject = singletonFactory.getObject();
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        this.singletonFactories.remove(beanName);
                    }
                }
            }
        }
        return (singletonObject != NULL_OBJECT ? singletonObject : null);
    }

看代码就是去从map中获取到该bean,获取不到则返回null,这里有几个map 需要注意下

/** Cache of singleton objects: bean name --> bean instance */
    private final Map singletonObjects = new ConcurrentHashMap(64);

    /** Names of beans that are currently in creation */
    private final Set singletonsCurrentlyInCreation =
            Collections.newSetFromMap(new ConcurrentHashMap(16));

/** Cache of early singleton objects: bean name --> bean instance */
    private final Map earlySingletonObjects = new HashMap(16);

/** Cache of singleton factories: bean name --> ObjectFactory */
    private final Map> singletonFactories = new HashMap>(16);

看代码,先去从singletonObjects中去获取,该map 存贮的是已经实例化完成的单例bean,获取到则返回,获取不到则继续看singletonsCurrentlyInCreation这个map ,这个map存贮的是正在创建的单例bean,因为是单例模式所以肯定不能创建重复啊,这时候会涉及到一个同步语句synchronized (this.singletonObjects) 锁住的是 singletonObjects避免在从早些时候的beanfatory获取该bean的时候有别的线程创建了该bean 注册到 singletonObjectsmap中。然后从earlySingletonObjects中获取该bean 获取不到的试试会去尝试 获取名称为该name的ObjectFactory,因为创建一个bean的时候可以单独为该bean创建一个ObjectFactory来存贮这个bean,若获取到ObjectFactory则获取这个bean ,然后会把这个bean加入到earlySingletonObjects中,从singletonFactories将其移除掉,因为这个bean将成为过去时即早些时候创建的bean。最后返回。

回到doGetBean方法,在取到的情况下会走getObjectForBeanInstance方法。这个我们待会修改下test代码再说,先看取不到bean的情况下会走

else {
            // Fail if we're already creating this bean instance:
            // We're assumably within a circular reference.
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            // Check if bean definition exists in this factory.
            BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // Not found -> check parent.
                String nameToLookup = originalBeanName(name);
                if (args != null) {
                    // Delegation to parent with explicit args.
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
            }

            if (!typeCheckOnly) {
                markBeanAsCreated(beanName);
            }

            try {
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);

                // Guarantee initialization of beans that the current bean depends on.
                String[] dependsOn = mbd.getDependsOn();
                if (dependsOn != null) {
                    for (String dependsOnBean : dependsOn) {
                        if (isDependent(beanName, dependsOnBean)) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
                        }
                        registerDependentBean(dependsOnBean, beanName);
                        getBean(dependsOnBean);
                    }
                }

                // Create bean instance.
                if (mbd.isSingleton()) {
                    sharedInstance = getSingleton(beanName, new ObjectFactory() {
                        @Override
                        public Object getObject() throws BeansException {
                            try {
                                return createBean(beanName, mbd, args);
                            }
                            catch (BeansException ex) {
                                // Explicitly remove instance from singleton cache: It might have been put there
                                // eagerly by the creation process, to allow for circular reference resolution.
                                // Also remove any beans that received a temporary reference to the bean.
                                destroySingleton(beanName);
                                throw ex;
                            }
                        }
                    });
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }

                else if (mbd.isPrototype()) {
                    // It's a prototype -> create a new instance.
                    Object prototypeInstance = null;
                    try {
                        beforePrototypeCreation(beanName);
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                        afterPrototypeCreation(beanName);
                    }
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }

                else {
                    String scopeName = mbd.getScope();
                    final Scope scope = this.scopes.get(scopeName);
                    if (scope == null) {
                        throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'");
                    }
                    try {
                        Object scopedInstance = scope.get(beanName, new ObjectFactory() {
                            @Override
                            public Object getObject() throws BeansException {
                                beforePrototypeCreation(beanName);
                                try {
                                    return createBean(beanName, mbd, args);
                                }
                                finally {
                                    afterPrototypeCreation(beanName);
                                }
                            }
                        });
                        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }
                    catch (IllegalStateException ex) {
                        throw new BeanCreationException(beanName,
                                "Scope '" + scopeName + "' is not active for the current thread; " +
                                "consider defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                                ex);
                    }
                }
            }
            catch (BeansException ex) {
                cleanupAfterBeanCreationFailure(beanName);
                throw ex;
            }
        }

 
 

第一句话的注释

// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.

大致意思就是避免循环创建一个bean,这里做个检查涉及到一个map属性

/** Names of beans that are currently in creation */
    private final ThreadLocal prototypesCurrentlyInCreation =
            new NamedThreadLocal("Prototype beans currently in creation");
 
 

保存的是当前正在创建的bean实例。检查过后会去检查这个bean是否存在了当前的factory

// Check if bean definition exists in this factory.

BeanFactory实例AbstractBeanFactory里面有parentBeanFactory的定义 可以说是beanfactory是链式结构的。

/** Parent bean factory, for bean inheritance support */
    private BeanFactory parentBeanFactory;

查找当前parentBeanFactory里面是否存在该实例bean。
查找不到的 情况下并且不是单单类型检查(需要去创建新的bean) 会先去标记这个bean创建了这里涉及到一个属性alreadyCreated

/** Names of beans that have already been created at least once */
    private final Set alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap(64));

接着去获取上篇博文中说的 从xml加载到内存的BeanDefinition,先是查找RootBeanDefinition
这里会涉及到一个map属性mergedBeanDefinitions

/** Map from bean name to merged RootBeanDefinition */
    private final Map mergedBeanDefinitions =
            new ConcurrentHashMap(64);

在没有查找到的情况下会继续查找最后会从

/** Map of bean definition objects, keyed by bean name */
    private final Map beanDefinitionMap = new ConcurrentHashMap(64);

属性中获取,在BeanDefinition装配完成的时候会将所有的beanDefinition放到这个map属性 中所以必然会取到BeanDefinition。返回后 如果RootBeanDefinition为空 则会根据返回的BeanDefinition去创建RootBeanDefinitionmbd = new RootBeanDefinition(bd);因为之前没有 它是最初的所以他就是RootBeanDefinition喽,(这就是老员工的优势 来的早呗哈哈哈哈)
构造好RootBeanDefinition会去 set它的scope 这里看一看到

默认scop设置是单例的

默认没设置scope的情况下就是单例的。
得到RootBeanDefinition 后定义为了

final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);

final类型的,可见此处后得到的RootBeanDefinition变量mbd 不会再变化了,也可以防止其它地方对它的修改。
此时又有一个判断该RootBeanDefinition的变量mbd是否是抽象类,因为抽象类是不可以实例化的,所以假如是抽象类则会抛出BeanIsAbstractException的异常。

protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, Object[] args)
            throws BeanDefinitionStoreException {

        if (mbd.isAbstract()) {
            throw new BeanIsAbstractException(beanName);
        }
    }

此时到了保证这个bean所依赖的bean都被初始化的时候,看代码中的一句注释

spring-beans深入源码之获取Bean的过程解析_第2张图片
Guarantee initialization of beans that the current bean depends on

截图中的这段就是去保证的,若得到的dependsOn数组不为空 则会继续去getBean dependsOn数组中的bean。逻辑和单独get一个bean是一样的。
  这会RootBeanDefinition的得到过程就全部完成了,到了需要将BeanDefinition转化成真正bean的时候了。单例的bean和原型的bean的走的过程是不一致的,先看我们的单例bean从bean

// Create bean instance.
                if (mbd.isSingleton()) {
                    sharedInstance = getSingleton(beanName, new ObjectFactory() {
                        @Override
                        public Object getObject() throws BeansException {
                            try {
                                return createBean(beanName, mbd, args);
                            }
                            catch (BeansException ex) {
                                // Explicitly remove instance from singleton cache: It might have been put there
                                // eagerly by the creation process, to allow for circular reference resolution.
                                // Also remove any beans that received a temporary reference to the bean.
                                destroySingleton(beanName);
                                throw ex;
                            }
                        }
                    });
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }
 
 

这里的getSingleton方法传入的参数用到了匿名内部类, 匿名内部类也就是没有名字的内部类,正因为没有名字,所以匿名内部类只能使用一次,它通常用来简化代码编写但使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口
在getSingleton方法中

public Object getSingleton(String beanName, ObjectFactory singletonFactory) {
        Assert.notNull(beanName, "'beanName' must not be null");
        synchronized (this.singletonObjects) {
            Object singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
                if (this.singletonsCurrentlyInDestruction) {
                    throw new BeanCreationNotAllowedException(beanName,
                            "Singleton bean creation not allowed while the singletons of this factory are in destruction " +
                            "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
                }
                beforeSingletonCreation(beanName);
                boolean newSingleton = false;
                boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = new LinkedHashSet();
                }
                try {
                    singletonObject = singletonFactory.getObject();
                    newSingleton = true;
                }
                catch (IllegalStateException ex) {
                    // Has the singleton object implicitly appeared in the meantime ->
                    // if yes, proceed with it since the exception indicates that state.
                    singletonObject = this.singletonObjects.get(beanName);
                    if (singletonObject == null) {
                        throw ex;
                    }
                }
                catch (BeanCreationException ex) {
                    if (recordSuppressedExceptions) {
                        for (Exception suppressedException : this.suppressedExceptions) {
                            ex.addRelatedCause(suppressedException);
                        }
                    }
                    throw ex;
                }
                finally {
                    if (recordSuppressedExceptions) {
                        this.suppressedExceptions = null;
                    }
                    afterSingletonCreation(beanName);
                }
                if (newSingleton) {
                    addSingleton(beanName, singletonObject);
                }
            }
            return (singletonObject != NULL_OBJECT ? singletonObject : null);
        }
    }

首先用到了同步语句块synchronized (this.singletonObjects),因为hashmap自身是非线程安全的,在创建过程中肯定要保证其线程安全性。这里有可以看到spring经典创建bean的三部曲,beforeSingletonCreationsingletonObject = singletonFactory.getObject();afterSingletonCreation,前期,中期和后期。
先看beforeSingletonCreation,前期工作一般做一些检查,哈哈代码十分简单我喜欢


protected void beforeSingletonCreation(String beanName) {
        if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }
    }

就是去将bean放入当前创建bean的set中和当前bean创建的检查被排除的中。好拗口 直接上属性原文注释

/** Names of beans that are currently in creation */
    private final Set singletonsCurrentlyInCreation =
            Collections.newSetFromMap(new ConcurrentHashMap(16));

    /** Names of beans currently excluded from in creation checks */
    private final Set inCreationCheckExclusions =
            Collections.newSetFromMap(new ConcurrentHashMap(16));

中间步骤singletonObject = singletonFactory.getObject();,这里其实就是调用传入的匿名内部类 重写的getObject方法,其实这和回调函数非常像。你传入ObjectFactory匿名内部类重写了getObject方法,此刻调用 是不是很像回调函数 。我们继续debug一下

spring-beans深入源码之获取Bean的过程解析_第3张图片
ObjectFactory getObject 方法回调

继续debug进去到createBean方法中

protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
        if (logger.isDebugEnabled()) {
            logger.debug("Creating instance of bean '" + beanName + "'");
        }
        RootBeanDefinition mbdToUse = mbd;

        // Make sure bean class is actually resolved at this point, and
        // clone the bean definition in case of a dynamically resolved Class
        // which cannot be stored in the shared merged bean definition.
        Class resolvedClass = resolveBeanClass(mbd, beanName);
        if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
            mbdToUse = new RootBeanDefinition(mbd);
            mbdToUse.setBeanClass(resolvedClass);
        }

        // Prepare method overrides.
        try {
            mbdToUse.prepareMethodOverrides();
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                    beanName, "Validation of method overrides failed", ex);
        }

        try {
            // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
            Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
            if (bean != null) {
                return bean;
            }
        }
        catch (Throwable ex) {
            throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                    "BeanPostProcessor before instantiation of bean failed", ex);
        }

        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isDebugEnabled()) {
            logger.debug("Finished creating instance of bean '" + beanName + "'");
        }
        return beanInstance;
    }

resolveBeanClass是保证class被解析了 直接看英文注释

// Make sure bean class is actually resolved at this point, and
        // clone the bean definition in case of a dynamically resolved Class
        // which cannot be stored in the shared merged bean definition.

接着是 重写的方法解析

// Prepare method overrides.
        try {
            mbdToUse.prepareMethodOverrides();
        }

其中重写的方法都是在解析bean definition 放到了

private MethodOverrides methodOverrides = new MethodOverrides();

中,接着到了 非常关键的一步就是 之前所说的BeanPostProcessors,看到没 所有的配置都有调用的地方 不是没有逻辑的,哈哈 看代码

// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
            Object bean = resolveBeforeInstantiation(beanName, mbdToUse);

接着到

/**
     * Apply before-instantiation post-processors, resolving whether there is a
     * before-instantiation shortcut for the specified bean.
     * @param beanName the name of the bean
     * @param mbd the bean definition for the bean
     * @return the shortcut-determined bean instance, or {@code null} if none
     */
    protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
        Object bean = null;
        if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
            // Make sure bean class is actually resolved at this point.
            if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
                Class targetType = determineTargetType(beanName, mbd);
                if (targetType != null) {
                    bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                    if (bean != null) {
                        bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                    }
                }
            }
            mbd.beforeInstantiationResolved = (bean != null);
        }
        return bean;
    }

spring-beans深入源码之获取Bean的过程解析_第4张图片
resolveBeforeInstantiation

非常重要的两个步骤,接着返回回去到最后一步,也是比较复杂的一步。

Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isDebugEnabled()) {
            logger.debug("Finished creating instance of bean '" + beanName + "'");
        }
        return beanInstance;

进去到

/**
     * Actually create the specified bean. Pre-creation processing has already happened
     * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
     * 

Differentiates between default bean instantiation, use of a * factory method, and autowiring a constructor. * @param beanName the name of the bean * @param mbd the merged bean definition for the bean * @param args explicit arguments to use for constructor or factory method invocation * @return a new instance of the bean * @throws BeanCreationException if the bean could not be created * @see #instantiateBean * @see #instantiateUsingFactoryMethod * @see #autowireConstructor */ protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) { // Instantiate the bean. BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { instanceWrapper = createBeanInstance(beanName, mbd, args); } final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null); Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); mbd.postProcessed = true; } } // Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isDebugEnabled()) { logger.debug("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } addSingletonFactory(beanName, new ObjectFactory() { @Override public Object getObject() throws BeansException { return getEarlyBeanReference(beanName, mbd, bean); } }); } // Initialize the bean instance. Object exposedObject = bean; try { populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { exposedObject = initializeBean(beanName, exposedObject, mbd); } } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } if (earlySingletonExposure) { Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set actualDependentBeans = new LinkedHashSet(dependentBeans.length); for (String dependentBean : dependentBeans) { if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); } } } } // Register bean as disposable. try { registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }

这个方法中涉及到BeanWrapper 首先从

/** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */
    private final Map factoryBeanInstanceCache =
            new ConcurrentHashMap(16);

移除掉这个bean,然后去创建 BeanInstance

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
        // Make sure bean class is actually resolved at this point.
        Class beanClass = resolveBeanClass(mbd, beanName);

        if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
        }

        if (mbd.getFactoryMethodName() != null)  {
            return instantiateUsingFactoryMethod(beanName, mbd, args);
        }

        // Shortcut when re-creating the same bean...
        boolean resolved = false;
        boolean autowireNecessary = false;
        if (args == null) {
            synchronized (mbd.constructorArgumentLock) {
                if (mbd.resolvedConstructorOrFactoryMethod != null) {
                    resolved = true;
                    autowireNecessary = mbd.constructorArgumentsResolved;
                }
            }
        }
        if (resolved) {
            if (autowireNecessary) {
                return autowireConstructor(beanName, mbd, null, null);
            }
            else {
                return instantiateBean(beanName, mbd);
            }
        }

        // Need to determine the constructor...
        Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
        if (ctors != null ||
                mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
                mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
            return autowireConstructor(beanName, mbd, ctors, args);
        }

        // No special handling: simply use no-arg constructor.
        return instantiateBean(beanName, mbd);
    }

接着到

protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
        try {
            Object beanInstance;
            final BeanFactory parent = this;
            if (System.getSecurityManager() != null) {
                beanInstance = AccessController.doPrivileged(new PrivilegedAction() {
                    @Override
                    public Object run() {
                        return getInstantiationStrategy().instantiate(mbd, beanName, parent);
                    }
                }, getAccessControlContext());
            }
            else {
                beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
            }
            BeanWrapper bw = new BeanWrapperImpl(beanInstance);
            initBeanWrapper(bw);
            return bw;
        }
        catch (Throwable ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
        }
    }
 
 

最重要的方法:


![getInstantiationStrategy](http://upload-images.jianshu.io/upload_images/2847417-1f8a3fced7c5f649.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

这里的getInstantiationStrategy 获取到的instantiationStrategy是

/** Strategy for creating bean instances */
    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

这里的策略模式采用的是CglibSubclassingInstantiationStrategy, cglib大家都只到吧 就是字节码装配成bean的工具包。
afterSingletonCreation 同样简单 我喜欢 哈哈哈 不在排除的bean set中 和将其从正在创建的bean set中移除
上代码:

protected void afterSingletonCreation(String beanName) {
        if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
            throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
        }
    }

今晚太晚了,还在公司 CglibSubclassingInstantiationStrategy加载bean的过程 决定明天下一篇博客写,回家睡觉喽。

你可能感兴趣的:(spring-beans深入源码之获取Bean的过程解析)