spring-beans深入源碼之獲取Bean的過程解析

上一篇博文大致說完了Bean Definition 從xml文件的載入過程,真正需要bean的時(shí)候還是要從BeanFactory get獲取的。接下來看一下bean的get過程。
查看test方法

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

這里的this.beanFactory 是上面setUp方法中創(chuàng)建的

this.beanFactory = new DefaultListableBeanFactory();

可以知道 setUp方法裝配了bean definition到了<b>BeanFactory</b>中,最后你需要的用到bean的時(shí)候還是需要從<b>BeanFactory</b>中獲取。
繼續(xù)debug進(jìn)入到

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

繼續(xù)進(jìn)入到獲取bean的主要方法

bean獲取的主要方法

第一行 final String beanName = transformedBeanName(name); 是對你傳入的bean的name的轉(zhuǎn)換,代碼內(nèi)部用到了BeanFactoryUtils.transformedBeanName(name)方法,該方法主要是去掉以String FACTORY_BEAN_PREFIX = "&";開頭的bean的name,截取<b>&</b>后面的部分,最后會(huì)查看private final Map<String, String> aliasMap = new ConcurrentHashMap<String, String>(16);別名map中是否已經(jīng)存在這個(gè)bean name 存在則沿用以前的bean name。接著繼續(xù)獲取bean 這里有一段代碼注釋// Eagerly check singleton cache for manually registered singletons. 大致意思就是先從已經(jīng)注冊到<b>BeanFactory</b>的單例的map里面去獲取這個(gè)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,這里有幾個(gè)map 需要注意下

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

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

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

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

看代碼,先去從singletonObjects中去獲取,該map 存貯的是已經(jīng)實(shí)例化完成的單例bean,獲取到則返回,獲取不到則繼續(xù)看singletonsCurrentlyInCreation這個(gè)map ,這個(gè)map存貯的是正在創(chuàng)建的單例bean,因?yàn)槭菃卫J剿钥隙ú荒軇?chuàng)建重復(fù)啊,這時(shí)候會(huì)涉及到一個(gè)同步語句synchronized (this.singletonObjects) 鎖住的是 singletonObjects避免在從早些時(shí)候的beanfatory獲取該bean的時(shí)候有別的線程創(chuàng)建了該bean 注冊到 singletonObjectsmap中。然后從earlySingletonObjects中獲取該bean 獲取不到的試試會(huì)去嘗試 獲取名稱為該name的ObjectFactory,因?yàn)閯?chuàng)建一個(gè)bean的時(shí)候可以單獨(dú)為該bean創(chuàng)建一個(gè)ObjectFactory來存貯這個(gè)bean,若獲取到ObjectFactory則獲取這個(gè)bean ,然后會(huì)把這個(gè)bean加入到earlySingletonObjects中,從singletonFactories將其移除掉,因?yàn)檫@個(gè)bean將成為過去時(shí)即早些時(shí)候創(chuàng)建的bean。最后返回。

回到<b>doGetBean</b>方法,在取到的情況下會(huì)走getObjectForBeanInstance方法。這個(gè)我們待會(huì)修改下test代碼再說,先看取不到bean的情況下會(huì)走

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<Object>() {
                        @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<Object>() {
                            @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.

大致意思就是避免循環(huán)創(chuàng)建一個(gè)bean,這里做個(gè)檢查涉及到一個(gè)map屬性

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

保存的是當(dāng)前正在創(chuàng)建的bean實(shí)例。檢查過后會(huì)去檢查這個(gè)bean是否存在了當(dāng)前的factory

// Check if bean definition exists in this factory.

<b>BeanFactory</b>實(shí)例<b>AbstractBeanFactory</b>里面有<b>parentBeanFactory</b>的定義 可以說是beanfactory是鏈?zhǔn)浇Y(jié)構(gòu)的。

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

查找當(dāng)前<b>parentBeanFactory</b>里面是否存在該實(shí)例bean。
查找不到的 情況下并且不是單單類型檢查(需要去創(chuàng)建新的bean) 會(huì)先去標(biāo)記這個(gè)bean創(chuàng)建了這里涉及到一個(gè)屬性<b>alreadyCreated </b>

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

接著去獲取上篇博文中說的 從xml加載到內(nèi)存的<b>BeanDefinition</b>,先是查找<b>RootBeanDefinition</b>
這里會(huì)涉及到一個(gè)map屬性<b>mergedBeanDefinitions </b>

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

在沒有查找到的情況下會(huì)繼續(xù)查找最后會(huì)從

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

屬性中獲取,在BeanDefinition裝配完成的時(shí)候會(huì)將所有的beanDefinition放到這個(gè)map屬性 中所以必然會(huì)取到BeanDefinition。返回后 如果<b>RootBeanDefinition</b>為空 則會(huì)根據(jù)返回的<b>BeanDefinition</b>去創(chuàng)建<b>RootBeanDefinition</b>mbd = new RootBeanDefinition(bd);因?yàn)橹皼]有 它是最初的所以他就是RootBeanDefinition嘍,(這就是老員工的優(yōu)勢 來的早唄哈哈哈哈)
構(gòu)造好<b>RootBeanDefinition</b>會(huì)去 set它的scope 這里看一看到

默認(rèn)scop設(shè)置是單例的

默認(rèn)沒設(shè)置scope的情況下就是單例的。
得到<b>RootBeanDefinition</b> 后定義為了

final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);

final類型的,可見此處后得到的<b>RootBeanDefinition</b>變量mbd 不會(huì)再變化了,也可以防止其它地方對它的修改。
此時(shí)又有一個(gè)判斷該<b>RootBeanDefinition</b>的變量mbd是否是抽象類,因?yàn)槌橄箢愂遣豢梢詫?shí)例化的,所以假如是抽象類則會(huì)拋出<b>BeanIsAbstractException</b>的異常。

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

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

此時(shí)到了保證這個(gè)bean所依賴的bean都被初始化的時(shí)候,看代碼中的一句注釋

Guarantee initialization of beans that the current bean depends on

截圖中的這段就是去保證的,若得到的dependsOn數(shù)組不為空 則會(huì)繼續(xù)去getBean dependsOn數(shù)組中的bean。邏輯和單獨(dú)get一個(gè)bean是一樣的。
  這會(huì)<b>RootBeanDefinition</b>的得到過程就全部完成了,到了需要將<b>BeanDefinition</b>轉(zhuǎn)化成真正bean的時(shí)候了。單例的bean和原型的bean的走的過程是不一致的,先看我們的單例bean從bean

// Create bean instance.
                if (mbd.isSingleton()) {
                    sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
                        @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);
                }

這里的<b>getSingleton</b>方法傳入的參數(shù)用到了<b>匿名內(nèi)部類</b>, <b>匿名內(nèi)部類也就是沒有名字的內(nèi)部類,正因?yàn)闆]有名字,所以匿名內(nèi)部類只能使用一次,它通常用來簡化代碼編寫但使用匿名內(nèi)部類還有個(gè)前提條件:必須繼承一個(gè)父類或?qū)崿F(xiàn)一個(gè)接口</b>
在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<Exception>();
                }
                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),因?yàn)閔ashmap自身是非線程安全的,在創(chuàng)建過程中肯定要保證其線程安全性。這里有可以看到spring經(jīng)典創(chuàng)建bean的三部曲,beforeSingletonCreation、singletonObject = singletonFactory.getObject();afterSingletonCreation,前期,中期和后期。
先看<b>beforeSingletonCreation</b>,前期工作一般做一些檢查,哈哈代碼十分簡單我喜歡


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

就是去將bean放入當(dāng)前創(chuàng)建bean的set中和當(dāng)前bean創(chuàng)建的檢查被排除的中。好拗口 直接上屬性原文注釋

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

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

中間步驟singletonObject = singletonFactory.getObject();,這里其實(shí)就是調(diào)用傳入的匿名內(nèi)部類 重寫的getObject方法,其實(shí)這和回調(diào)函數(shù)非常像。你傳入ObjectFactory匿名內(nèi)部類重寫了getObject方法,此刻調(diào)用 是不是很像回調(diào)函數(shù) 。我們繼續(xù)debug一下

ObjectFactory getObject 方法回調(diào)

繼續(xù)debug進(jìn)去到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;
    }

<b>resolveBeanClass</b>是保證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();

中,接著到了 非常關(guān)鍵的一步就是 之前所說的<b>BeanPostProcessors</b>,看到?jīng)] 所有的配置都有調(diào)用的地方 不是沒有邏輯的,哈哈 看代碼

// 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;
    }

resolveBeforeInstantiation

非常重要的兩個(gè)步驟,接著返回回去到最后一步,也是比較復(fù)雜的一步。

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

進(jìn)去到

/**
     * Actually create the specified bean. Pre-creation processing has already happened
     * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
     * <p>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<Object>() {
                @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<String> actualDependentBeans = new LinkedHashSet<String>(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;
    }

這個(gè)方法中涉及到<b>BeanWrapper</b> 首先從

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

移除掉這個(gè)bean,然后去創(chuàng)建 <b>BeanInstance</b>

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<Object>() {
                    @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大家都只到吧 就是字節(jié)碼裝配成bean的工具包。
afterSingletonCreation 同樣簡單 我喜歡 哈哈哈 不在排除的bean set中 和將其從正在創(chuàng)建的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");
        }
    }

今晚太晚了,還在公司 <b>CglibSubclassingInstantiationStrategy</b>加載bean的過程 決定明天下一篇博客寫,回家睡覺嘍。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,537評(píng)論 19 139
  • Spring 的 bean 初始化過程 前言 Spring 框架最基礎(chǔ)來說, 是一個(gè) DI(依賴注入) 框架. 我...
    yxc023閱讀 13,313評(píng)論 4 9
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan閱讀 4,488評(píng)論 2 7
  • 最近,新華網(wǎng)對今年高考的36名狀元報(bào)考志愿填報(bào)情況進(jìn)行了調(diào)查,結(jié)果顯示無一報(bào)考醫(yī)學(xué)類專業(yè)。頓時(shí)輿論嘩然,各方...
    阿基米德DWAD閱讀 257評(píng)論 0 3
  • 上周的睡前說系列集中在算法信息論和圖靈機(jī)的問題上,今天打算輕松一下,寫點(diǎn)不怎么燒腦的話題。當(dāng)然,主要是今天白天已經(jīng)...
    LostAbaddon閱讀 1,169評(píng)論 7 6

友情鏈接更多精彩內(nèi)容