Spring Bean的創(chuàng)建過(guò)程及相關(guān)擴(kuò)展點(diǎn)

首先,我們最基本的常識(shí)是從ApplicationContext入手,從AbstractApplicationContext的refresh()作為入口,找到finishBeanFactoryInitialization()方法,這個(gè)方法的作用是實(shí)例化非懶加載的Bean實(shí)例。那么我們就可以進(jìn)入AbstractBeanFactory的getBean()方法。

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

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return doGetBean(name, requiredType, null, false);
    }

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

下面來(lái)看看doGetBean()方法:

protected <T> T doGetBean(
            String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
            throws BeansException {
    // 轉(zhuǎn)換一下,比如有別名、&開頭的名字等這些請(qǐng)求,全部都轉(zhuǎn)換成統(tǒng)一的beanName
        String beanName = transformedBeanName(name);
        Object bean;

        // Eagerly check singleton cache for manually registered singletons.
    // 從緩存中去。先從一級(jí)緩存中取,不行再?gòu)亩?jí)緩存取、最后從三級(jí)緩存取
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            if (logger.isTraceEnabled()) {
                if (isSingletonCurrentlyInCreation(beanName)) {
                    logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                            "' that is not fully initialized yet - a consequence of a circular reference");
                }
                else {
                    logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
                }
            }
      // 擴(kuò)展點(diǎn)---------擴(kuò)展點(diǎn)-----------擴(kuò)展點(diǎn)-------------
      // 判斷name是不是&開頭的,如果是&開頭的話,并且sharedInstance是FactoryBean類型,就直接返回
      // 如果不是&開頭,也不是FactoryBean類型,直接返回
      // 如果不是&開頭,是FactoryBean類型,調(diào)用getObject()方法返回Bean對(duì)象
      // 也就是說(shuō),我們可以通過(guò)實(shí)現(xiàn)FactoryBean來(lái)創(chuàng)建Bean對(duì)象
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }

        else {
            // Fail if we're already creating this bean instance:
            // We're assumably within a circular reference.
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }
      // 下面是從父容器中找對(duì)應(yīng)的Bean實(shí)例
      // 注意:容器是存在父子關(guān)系的。spring mvc就是一個(gè)父子關(guān)系的容器
            // 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 (parentBeanFactory instanceof AbstractBeanFactory) {
                    return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                            nameToLookup, requiredType, args, typeCheckOnly);
                }
                else if (args != null) {
                    // Delegation to parent with explicit args.
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else if (requiredType != null) {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
                else {
                    return (T) parentBeanFactory.getBean(nameToLookup);
                }
            }

            if (!typeCheckOnly) {
                markBeanAsCreated(beanName);
            }
      // 下面準(zhǔn)備查找當(dāng)前Bean對(duì)象依賴的其他Bean。比如在創(chuàng)建當(dāng)前這個(gè)Bean之前必須要?jiǎng)?chuàng)建另外一個(gè)Bean
            try {
                RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);
        // 找到所有在這個(gè)Bean創(chuàng)建之前一定要?jiǎng)?chuàng)建出來(lái)的依賴,依次調(diào)用getBean()創(chuàng)建
                // Guarantee initialization of beans that the current bean depends on.
                String[] dependsOn = mbd.getDependsOn();
                if (dependsOn != null) {
                    for (String dep : dependsOn) {
                        if (isDependent(beanName, dep)) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                        }
                        registerDependentBean(dep, beanName);
                        try {
                            getBean(dep);
                        }
                        catch (NoSuchBeanDefinitionException ex) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                        }
                    }
                }

                // Create bean instance.
                if (mbd.isSingleton()) {
          // ******這是重點(diǎn)******這是重點(diǎn)******這是重點(diǎn)******這是重點(diǎn)******
          // 這里理解起來(lái)有點(diǎn)繞。注意這個(gè)getSingleton(String beanName,ObjectFactory<?> singletonFactory)方法。
          // 第二個(gè)參數(shù)使用lamble表達(dá)式,可以先忽略
          // getSingleton()里面就做了兩件事情:
          // 1.通過(guò)lamble表達(dá)式創(chuàng)建Bean對(duì)象
          // 2.把創(chuàng)建好的Bean對(duì)象放到一級(jí)緩存中
          // 最后返回創(chuàng)建好的Bean對(duì)象
                    sharedInstance = getSingleton(beanName, () -> {
                        try {
              // 一定要先理清楚getSingleton()方法,再來(lái)看createBean()方法
              // ******這是重點(diǎn)******這是重點(diǎn)******這是重點(diǎn)******這是重點(diǎn)*****
                            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.
                            // 沒創(chuàng)建成功就要銷毀。不是重點(diǎn)
              destroySingleton(beanName);
                            throw ex;
                        }
                    });
          // 同樣的,檢查一下是不是FactoryBean,并且name是否以&開頭
          // 擴(kuò)展點(diǎn)---------擴(kuò)展點(diǎn)-----------擴(kuò)展點(diǎn)-------------
          // 判斷name是不是&開頭的,如果是&開頭的話,并且sharedInstance是FactoryBean類型,就直接返回
          // 如果不是&開頭,也不是FactoryBean類型,直接返回
          // 如果不是&開頭,是FactoryBean類型,調(diào)用getObject()方法返回Bean對(duì)象
          // 也就是說(shuō),我們可以通過(guò)實(shí)現(xiàn)FactoryBean來(lái)創(chuàng)建Bean對(duì)象
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }
        // 其實(shí)到這里就可以不用看非單例的情況了,因?yàn)榛径疾畈欢唷V攸c(diǎn)關(guān)注如何創(chuàng)建Bean對(duì)象。
                else if (mbd.isPrototype()) {
                    // It's a prototype -> create a new instance.
                    Object prototypeInstance = null;
                    try {
                        beforePrototypeCreation(beanName);
            // 還是創(chuàng)建Bean對(duì)象,這是重點(diǎn)
            // ******這是重點(diǎn)******這是重點(diǎn)******這是重點(diǎn)******這是重點(diǎn)*****
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                        afterPrototypeCreation(beanName);
                    }
          // 同上,檢查是否是FactoryBean
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }
        // 這里也一樣,其他scope,重點(diǎn)還是在createBean()
                else {
                    String scopeName = mbd.getScope();
                    if (!StringUtils.hasLength(scopeName)) {
                        throw new IllegalStateException("No scope name defined for bean ′" + beanName + "'");
                    }
                    Scope scope = this.scopes.get(scopeName);
                    if (scope == null) {
                        throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                    }
                    try {
                        Object scopedInstance = scope.get(beanName, () -> {
                            beforePrototypeCreation(beanName);
                            try {
                // 重點(diǎn)都在這里
                // ******這是重點(diǎn)******這是重點(diǎn)******這是重點(diǎn)******這是重點(diǎn)*****
                                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;
            }
        }
  //下面都不是重點(diǎn),可忽略
        // Check if required type matches the type of the actual bean instance.
        if (requiredType != null && !requiredType.isInstance(bean)) {
            try {
                T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
                if (convertedBean == null) {
                    throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
                }
                return convertedBean;
            }
            catch (TypeMismatchException ex) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Failed to convert bean '" + name + "' to required type '" +
                            ClassUtils.getQualifiedName(requiredType) + "'", ex);
                }
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
        }
        return (T) bean;
    }

下面簡(jiǎn)單分析一下getSingleton():

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
        Assert.notNull(beanName, "Bean name must not be null");
        synchronized (this.singletonObjects) {
      // 先從一級(jí)緩存中取,先試試
            Object singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
                if (this.singletonsCurrentlyInDestruction) {
                    throw new BeanCreationNotAllowedException(beanName,
                            "Singleton bean creation not allowed while 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 + "'");
                }
        // 這不用看,就是做一個(gè)數(shù)據(jù)校驗(yàn)
                beforeSingletonCreation(beanName);
                boolean newSingleton = false;
                boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = new LinkedHashSet<>();
                }
                try {
          // ******這是重點(diǎn)******這是重點(diǎn)******這是重點(diǎn)******這是重點(diǎn)*****
          // 這里就是調(diào)用lamble表示式里面的邏輯了,千萬(wàn)要理清楚
          // lamble表達(dá)式里面就是做了createBean()的邏輯
                    singletonObject = singletonFactory.getObject();
                    newSingleton = true;
                }
        // 處理創(chuàng)建Bean對(duì)象出異常的情況,不用管
                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) {
          // 最后就是把創(chuàng)建好的Bean對(duì)象放到一級(jí)緩存中。因?yàn)檫@個(gè)Bean對(duì)象已經(jīng)是可以安全發(fā)布的了。
                    addSingleton(beanName, singletonObject);
                }
            }
      // 返回創(chuàng)建好的Bean對(duì)象
            return singletonObject;
        }
    }

核心重點(diǎn)createBean()方法:

@Override
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {

        if (logger.isTraceEnabled()) {
            logger.trace("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 {
            // ********重點(diǎn)1,這是一個(gè)擴(kuò)展點(diǎn),此時(shí)還沒有任何Bean實(shí)例被創(chuàng)建出來(lái)
      // ********這里就是把Bean的創(chuàng)建機(jī)會(huì)開放給開發(fā)者
            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);
        }

        try {
      // 如果開發(fā)者自己不創(chuàng)建Bean對(duì)象,那么就spring自己來(lái)親自處理
      // 重點(diǎn)2,這是spring框架創(chuàng)建Bean的過(guò)程
            Object beanInstance = doCreateBean(beanName, mbdToUse, args);
            if (logger.isTraceEnabled()) {
                logger.trace("Finished creating instance of bean '" + beanName + "'");
            }
            return beanInstance;
        }
        catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
            // A previously detected exception with proper bean creation context already,
            // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
            throw ex;
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
        }
    }

擴(kuò)展點(diǎn)1:開發(fā)者自己創(chuàng)建Bean

@Nullable
    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) {
          // 這里就是創(chuàng)建Bean的入口
                    bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                    if (bean != null) {
            // 如果真的把Bean實(shí)例創(chuàng)建出來(lái)了,那么再繼續(xù)后續(xù)的生命周期的邏輯調(diào)用
                        bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                    }
                }
            }
            mbd.beforeInstantiationResolved = (bean != null);
        }
        return bean;
    }
@Nullable
    protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
      // 一定要是InstantiationAwareBeanPostProcessor的實(shí)現(xiàn)類,才會(huì)在Bean沒有實(shí)例化的時(shí)候被調(diào)用
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }
@Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
            throws BeansException {

        Object result = existingBean;
    // 這里面可以對(duì)已經(jīng)創(chuàng)建出來(lái)的Bean實(shí)例增強(qiáng)
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessAfterInitialization(result, beanName);
            if (current == null) {
                return result;
            }
            result = current;
        }
        return result;
    }

1.實(shí)現(xiàn)了InstantiationAwareBeanPostProcessor接口的postProcessBeforeInstantiation()方法,就有機(jī)會(huì)自己創(chuàng)建Bean對(duì)象

2.實(shí)現(xiàn)了BeanPostProcessor接口的postProcessAfterInitialization()方法就能在Bean對(duì)象創(chuàng)建出來(lái)后,還有機(jī)會(huì)對(duì)創(chuàng)建出來(lái)的Bean對(duì)象進(jìn)行增強(qiáng)或者擴(kuò)展。注意:可以在這個(gè)點(diǎn)做AOP增強(qiáng)。

創(chuàng)建Bean實(shí)例

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {

        // Instantiate the bean.
        BeanWrapper instanceWrapper = null;
    // 如果是單例
        if (mbd.isSingleton()) {
      // 清除緩存
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        if (instanceWrapper == null) {
      // 創(chuàng)建Bean實(shí)例,這個(gè)instanceWrapper是已經(jīng)被包裝的對(duì)象了
      // 多種創(chuàng)建Bean的方法,了解后可以更靈活地創(chuàng)建Bean對(duì)象
      // *****這是重點(diǎn)***********這是重點(diǎn)***********這是重點(diǎn)******
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        Object bean = instanceWrapper.getWrappedInstance();
        Class<?> beanType = instanceWrapper.getWrappedClass();
        if (beanType != NullBean.class) {
            mbd.resolvedTargetType = beanType;
        }

        // Allow post-processors to modify the merged bean definition.
        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
          // 擴(kuò)展點(diǎn)
          // 解析@Autowired,@Value,@Inject注解,把對(duì)應(yīng)的字段和方法解析好設(shè)置進(jìn)BeanDefinition
          // 入口在AutowiredAnnotationBeanPostProcessor類中,可查看構(gòu)造函數(shù)
          // *****這是重點(diǎn)***********這是重點(diǎn)***********這是重點(diǎn)******
                    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                }
                catch (Throwable ex) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            "Post-processing of merged bean definition failed", ex);
                }
                mbd.postProcessed = true;
            }
        }

        // Eagerly cache singletons to be able to resolve circular references
        // even when triggered by lifecycle interfaces like BeanFactoryAware.
    // 如果這個(gè)Bean定義是單例,并且允許循環(huán)依賴,并且正在創(chuàng)建當(dāng)中,那么就允許提前暴露
        boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                isSingletonCurrentlyInCreation(beanName));
        if (earlySingletonExposure) {
            if (logger.isTraceEnabled()) {
                logger.trace("Eagerly caching bean '" + beanName +
                        "' to allow for resolving potential circular references");
            }
      // AOP入口,方便增強(qiáng)Bean。此時(shí)的Bean還沒有設(shè)置屬性,正好可以在其他Bean依賴它的時(shí)候通過(guò)getBean方法從第三級(jí)緩存中取出來(lái);在這個(gè)過(guò)程中可以對(duì)Bean進(jìn)行增強(qiáng)。
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }

        // Initialize the bean instance.
        Object exposedObject = bean;
        try {
      // 設(shè)置屬性值,通過(guò)屬性名和字段類型,從IOC容器中g(shù)etBean取值
            populateBean(beanName, mbd, instanceWrapper);
      // 調(diào)用初始化方法;先處理Aware結(jié)尾的接口,比如BeanNameAware,BeanClassLoaderAware,BeanFactoryAware接口;
      // 先調(diào)用postProcessBeforeInitialization
      // 執(zhí)行初始化方法;InitializingBean接口的afterPropertiesSet方法;還有自定義的初始化方法,比如@PostConstruct注解的方法,init-method配置的方法名
      // 再調(diào)用postProcessAfterInitialization
            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<>(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 " +
                                "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
                    }
                }
            }
        }

        // Register bean as disposable.
        try {
      // 注冊(cè)銷毀方法;比如@PreDestroy注解的方法,或者實(shí)現(xiàn)了DisposableBean接口的實(shí)現(xiàn),還有就是配置的destroy-method方法
            registerDisposableBeanIfNecessary(beanName, bean, mbd);
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
        }
    // 返回Bean實(shí)例
        return exposedObject;
    }

創(chuàng)建Bean實(shí)例createBeanInstance

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
        // Make sure bean class is actually resolved at this point.
    // 通過(guò)BeanDefinition和beanName獲取Class
        Class<?> beanClass = resolveBeanClass(mbd, beanName);
    // 如果這個(gè)類的修飾符不是pubic,那么直接拋異常
        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());
        }
    // 檢查有沒有指定的創(chuàng)造Bean實(shí)例的方法
    // beanDefinition.setInstanceSupplier(SupplierBean::createUser);
        Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
        if (instanceSupplier != null) {
            return obtainFromSupplier(instanceSupplier, beanName);
        }
    // 檢查是否有工廠方法。包括靜態(tài)工廠、實(shí)例工廠、@Bean這種方式也會(huì)被轉(zhuǎn)換成工廠方法
        if (mbd.getFactoryMethodName() != null) {
            return instantiateUsingFactoryMethod(beanName, mbd, args);
        }

        // Shortcut when re-creating the same bean...
    // 構(gòu)造器實(shí)例化
    // 快速實(shí)例化對(duì)象,所謂的快速實(shí)例化對(duì)象,其實(shí)就是使用了緩存
        boolean resolved = false;
        boolean autowireNecessary = false;
    // 外部化參數(shù),只能當(dāng)無(wú)外部參數(shù)時(shí)才使用緩存。不推薦使用外部化參數(shù)
        if (args == null) {
            synchronized (mbd.constructorArgumentLock) {
                if (mbd.resolvedConstructorOrFactoryMethod != null) {
          // 是否使用緩存,其中autowireNecessary表示是否使用有參構(gòu)造器
                    resolved = true;
                    autowireNecessary = mbd.constructorArgumentsResolved;
                }
            }
        }
    // 使用緩存,其中autowireNecessary表示是否使用有參構(gòu)造器
        if (resolved) {
            if (autowireNecessary) {
        // 這個(gè)情況就是使用了已經(jīng)解析好的BeanDefinition,直接從BeanDefinition中獲取構(gòu)造函數(shù)和參數(shù)
        // 比如Property模式的時(shí)候,就會(huì)調(diào)用這個(gè)邏輯創(chuàng)建Bean
                return autowireConstructor(beanName, mbd, null, null);
            }
            else {
        // 反射創(chuàng)建對(duì)象實(shí)例
                return instantiateBean(beanName, mbd);
            }
        }

        // Candidate constructors for autowiring?
        Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
        if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
                mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
      // @Autowire注解的構(gòu)造函數(shù),多個(gè)構(gòu)造函數(shù)
            return autowireConstructor(beanName, mbd, ctors, args);
        }

        // Preferred constructors for default construction?
        ctors = mbd.getPreferredConstructors();
        if (ctors != null) {
      // @Autowire注解的構(gòu)造函數(shù),默認(rèn)的構(gòu)造函數(shù)
            return autowireConstructor(beanName, mbd, ctors, null);
        }

        // No special handling: simply use no-arg constructor.
    // 反射創(chuàng)建對(duì)象實(shí)例
        return instantiateBean(beanName, mbd);
    }

總結(jié)一下就是:

1.先看看有沒有指定的工廠方法創(chuàng)建對(duì)象;比如Supplier,factory-method

2.其次匹配構(gòu)造函數(shù);這都是自定匹配的

3.最終就是反射無(wú)參構(gòu)造函數(shù)創(chuàng)建對(duì)象

// 這個(gè)擴(kuò)展點(diǎn)其實(shí)是用來(lái)增強(qiáng)BeanDefinition。比如AutowiredAnnotationBeanPostProcessor就是用來(lái)解析@Autowired注解的,方便后面給對(duì)象屬性賦值
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
   for (BeanPostProcessor bp : getBeanPostProcessors()) {
      if (bp instanceof MergedBeanDefinitionPostProcessor) {
        // MergedBeanDefinitionPostProcessor子類可實(shí)現(xiàn)BeanDefinition的擴(kuò)展
         MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
         bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
      }
   }
}

設(shè)置Bean對(duì)象屬性值

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
        if (bw == null) {
            if (mbd.hasPropertyValues()) {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
            }
            else {
                // Skip property population phase for null instance.
                return;
            }
        }

        // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
        // state of the bean before properties are set. This can be used, for example,
        // to support styles of field injection.
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
          // ********擴(kuò)展點(diǎn)**********擴(kuò)展點(diǎn)**********擴(kuò)展點(diǎn)**********擴(kuò)展點(diǎn)**
          // 一看這就是擴(kuò)展點(diǎn),一旦postProcessAfterInstantiation返回false,那么直接就跳出不會(huì)繼續(xù)執(zhí)行設(shè)置相關(guān)屬性值了
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                        return;
                    }
                }
            }
        }

        PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

        int resolvedAutowireMode = mbd.getResolvedAutowireMode();
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
            MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
            // Add property values based on autowire by name if applicable.
            if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
        // 根據(jù)name查找屬性值,其實(shí)里面也是通過(guò)getBean()獲取屬性值
                autowireByName(beanName, mbd, bw, newPvs);
            }
            // Add property values based on autowire by type if applicable.
            if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
        // 根據(jù)類型查找,其實(shí)里面也是通過(guò)getBean()獲取屬性值
                autowireByType(beanName, mbd, bw, newPvs);
            }
            pvs = newPvs;
        }

        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
        boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

        PropertyDescriptor[] filteredPds = null;
        if (hasInstAwareBpps) {
            if (pvs == null) {
                pvs = mbd.getPropertyValues();
            }
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
          // ******又是擴(kuò)展點(diǎn)******又是擴(kuò)展點(diǎn)******又是擴(kuò)展點(diǎn)******又是擴(kuò)展點(diǎn)****
          // 通過(guò)postProcessProperties可以攔截具體的屬性并賦值
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                    if (pvsToUse == null) {
                        if (filteredPds == null) {
                            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                        }
            // ******又是擴(kuò)展點(diǎn)******又是擴(kuò)展點(diǎn)******又是擴(kuò)展點(diǎn)******又是擴(kuò)展點(diǎn)****
            // 如果沒有在postProcessProperties進(jìn)行擴(kuò)展,可以在postProcessPropertyValues上擴(kuò)展
                        pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        if (pvsToUse == null) {
                            return;
                        }
                    }
                    pvs = pvsToUse;
                }
            }
        }
        if (needsDepCheck) {
            if (filteredPds == null) {
                filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            }
            checkDependencies(beanName, mbd, filteredPds, pvs);
        }

        if (pvs != null) {
      // 賦值,不用管
            applyPropertyValues(beanName, mbd, bw, pvs);
        }
    }

初始化Bean實(shí)例:

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                invokeAwareMethods(beanName, bean);
                return null;
            }, getAccessControlContext());
        }
        else {
      // 調(diào)用Aware相關(guān)接口;擴(kuò)展點(diǎn),可以用開獲取Bean名稱、類加載器、容器實(shí)例
            invokeAwareMethods(beanName, bean);
        }

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
      // 前置處理;擴(kuò)展點(diǎn),可以用來(lái)織入功能實(shí)現(xiàn)AOP
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }

        try {
      // 初始化;用來(lái)調(diào)用InitializingBean接口、@PostConstruct注解方法、init-method方法
            invokeInitMethods(beanName, wrappedBean, mbd);
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    (mbd != null ? mbd.getResourceDescription() : null),
                    beanName, "Invocation of init method failed", ex);
        }
        if (mbd == null || !mbd.isSynthetic()) {
      // 后置處理;擴(kuò)展點(diǎn),可以用來(lái)織入功能實(shí)現(xiàn)AOP
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }

        return wrappedBean;
    }
// 處理BeanNameAware、BeanClassLoaderAware、BeanFactoryAware接口
private void invokeAwareMethods(String beanName, Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ClassLoader bcl = getBeanClassLoader();
                if (bcl != null) {
                    ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
                }
            }
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
            }
        }
    }

@Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
            throws BeansException {

        Object result = existingBean;
    // AOP入口
    // *****擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)****
    // 實(shí)現(xiàn)BeanPostProcessor接口postProcessBeforeInitialization()方法,可對(duì)初始化前的Bean實(shí)例進(jìn)行攔截
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessBeforeInitialization(result, beanName);
            if (current == null) {
                return result;
            }
            result = current;
        }
        return result;
    }
//*****擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)****
// 初始化Bean的三種方式:
// 1.實(shí)現(xiàn)InitializingBean接口afterPropertiesSet()
// 2.@PostConstruct注解
// 3.xml配置init-method屬性
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
            throws Throwable {
  // 調(diào)用InitializingBean接口afterPropertiesSet()初始化
        boolean isInitializingBean = (bean instanceof InitializingBean);
        if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
            if (logger.isTraceEnabled()) {
                logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
            }
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                        ((InitializingBean) bean).afterPropertiesSet();
                        return null;
                    }, getAccessControlContext());
                }
                catch (PrivilegedActionException pae) {
                    throw pae.getException();
                }
            }
            else {
                ((InitializingBean) bean).afterPropertiesSet();
            }
        }
  // 調(diào)用init-method指定的方法;就是反射執(zhí)行
  // @PostConstruct注解在上面applyMergedBeanDefinitionPostProcessors()擴(kuò)展BeanDefinition的時(shí)候被解析后設(shè)置到BeanDefinition中去了,可查看InitDestroyAnnotationBeanPostProcessor
        if (mbd != null && bean.getClass() != NullBean.class) {
            String initMethodName = mbd.getInitMethodName();
            if (StringUtils.hasLength(initMethodName) &&
                    !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                    !mbd.isExternallyManagedInitMethod(initMethodName)) {
                invokeCustomInitMethod(beanName, bean, mbd);
            }
        }
    }

@Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
            throws BeansException {

        Object result = existingBean;
    // AOP入口
    // *****擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)****
    // 實(shí)現(xiàn)BeanPostProcessor接口postProcessAfterInitialization()方法,可對(duì)初始化前的Bean實(shí)例進(jìn)行攔截
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessAfterInitialization(result, beanName);
            if (current == null) {
                return result;
            }
            result = current;
        }
        return result;
    }

注冊(cè)銷毀方法

// *****擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)*********擴(kuò)展點(diǎn)****
// 銷毀方法有三種:
// 1.實(shí)現(xiàn)DisposableBean接口的destroy()方法
// 2.@PreDestroy注解
// 3.xml配置destroy-method
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
        AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
        if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
            if (mbd.isSingleton()) {
                // Register a DisposableBean implementation that performs all destruction
                // work for the given bean: DestructionAwareBeanPostProcessors,
                // DisposableBean interface, custom destroy method.
                // 注冊(cè)實(shí)現(xiàn)了DisposableBean接口
        registerDisposableBean(beanName,
                        new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
            }
            else {
        // 針對(duì)destroy-method配置;其實(shí)@PreDestroy注解會(huì)在applyMergedBeanDefinitionPostProcessors()擴(kuò)展BeanDefinition的時(shí)候被解析后設(shè)置到BeanDefinition中去了,可查看InitDestroyAnnotationBeanPostProcessor
                // A bean with a custom scope...
                Scope scope = this.scopes.get(mbd.getScope());
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
                }
                scope.registerDestructionCallback(beanName,
                        new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
            }
        }
    }

總結(jié)一下:getBean()

  • doGetBean()

      **1.先從緩存中獲取**
    
    • getSingleton():看看緩存中是否有Bean對(duì)象;逐步從一級(jí)緩存、二級(jí)緩存、三級(jí)緩存中取;這個(gè)要和Bean實(shí)例化后addSingleton()結(jié)合起來(lái)看;這個(gè)getSingleton()是可以從三級(jí)緩存中創(chuàng)建代理對(duì)象的。

    • getObjectForBeanInstance():如果是以“&”開頭的beanName,那么就返回FactoryBean對(duì)象;否則,如果這個(gè)Bean對(duì)象不是FactoryBean的話,就直接返回;如果是FactoryBean,那么就調(diào)用FactoryBean的getObject()返回目標(biāo)對(duì)象。

      2.從父容器中獲取

    • 如果上面的getSingleton()獲取不到Bean對(duì)象,那么就要從父容器中g(shù)etBean()

      3.創(chuàng)建DependsOn對(duì)象

    • 如果沒有父容器或者父容器也拿不到Bean對(duì)象,那么就先計(jì)算該目標(biāo)對(duì)象的DependsOn,也就是依賴,看看有哪些Bean是需要在這個(gè)對(duì)象創(chuàng)建之前要?jiǎng)?chuàng)建的。也是通過(guò)getBean()觸發(fā)創(chuàng)建邏輯。

      4.創(chuàng)建Bean對(duì)象

    • 最后就是getSingleton()邏輯中執(zhí)行創(chuàng)建Bean的邏輯;里面會(huì)有一個(gè)ObjectFactory,里面最終調(diào)用的是createBean方法創(chuàng)建Bean。創(chuàng)建好的Bean最終被添加到一級(jí)緩存中。

      4.1:前置InstantiationAwareBeanPostProcessor

      • resolveBeforeInstantiation():在Bean實(shí)例化之前,給出擴(kuò)展點(diǎn)讓開發(fā)者自己有機(jī)會(huì)創(chuàng)建Bean實(shí)例??捎糜贏OP切入創(chuàng)建代理對(duì)象。

      4.2:真正的創(chuàng)建Bean實(shí)例

      • doCreateBean():這里面完成了Bean的創(chuàng)建、BeanDefinition的擴(kuò)展、AOP的切入、屬性值的設(shè)置、初始化的執(zhí)行、銷毀方法的注冊(cè)

        4.2.1:創(chuàng)建Bean實(shí)例

        • createBeanInstance():分別通過(guò)工廠方法、有參構(gòu)造、無(wú)參構(gòu)造、反射等方法創(chuàng)建Bean實(shí)例

        • obtainFromSupplier():工廠方法

        • instantiateUsingFactoryMethod():工廠方法,factory-method配置。靜態(tài)工廠、實(shí)例工廠。

        • autowireConstructor():有參構(gòu)造、無(wú)參構(gòu)造

        • instantiateBean():默認(rèn)反射

        4.2.2:BeanDefinition的擴(kuò)展

        • applyMergedBeanDefinitionPostProcessors():MergedBeanDefinitionPostProcessor實(shí)現(xiàn)類可以重新設(shè)置BeanDefinition。這里最直接的應(yīng)用就是針對(duì)@Autowired、@Value、@Inject注解

        4.2.3:AOP的切入

        • addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)):這個(gè)就是把剛剛創(chuàng)建出來(lái)、還沒有對(duì)屬性賦值的Bean實(shí)例放到三級(jí)緩存中,給它指定SmartInstantiationAwareBeanPostProcessor子類增強(qiáng)。也就是說(shuō),在這個(gè)階段實(shí)現(xiàn)SmartInstantiationAwareBeanPostProcessor,就可以針對(duì)目標(biāo)Bean創(chuàng)建Proxy代理。

        4.2.4:屬性值的設(shè)置

        • populateBean():設(shè)置屬性值。這里面同樣也會(huì)去IOC容器中找屬性對(duì)應(yīng)的Bean實(shí)例。在這里的話,也有一個(gè)擴(kuò)展點(diǎn),就是InstantiationAwareBeanPostProcessor子類可以自定義是否交由spring設(shè)置屬性值、修改指定的屬性值。

        4.2.5:初始化的執(zhí)行

        • initializeBean():這里面就是開始準(zhǔn)備初始化的生命周期了。執(zhí)行Aware接口邏輯、BeforeInitialization、執(zhí)行初始化方法、AfterInitialization等邏輯的執(zhí)行。
          • invokeAwareMethods():分別調(diào)用BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
          • applyBeanPostProcessorsBeforeInitialization():調(diào)用BeanPostProcessor的postProcessBeforeInitialization方法;AOP的織入點(diǎn)
          • invokeInitMethods():調(diào)用InitializingBean.afterPropertiesSet(),@PostConstruct注解方法,Init-method配置的目標(biāo)方法
          • applyBeanPostProcessorsAfterInitialization():調(diào)用BeanPostProcessor的postProcessAfetrInitialization方法;AOP的織入點(diǎn)

        4.2.6:銷毀方法的注冊(cè)

        • registerDisposableBeanIfNecessary():調(diào)用DisposableBean的實(shí)現(xiàn)類,@PreDestory注解的方法,destory-method配置的目標(biāo)方法
    • getObjectForBeanInstance():如果是以“&”開頭的beanName,那么就返回FactoryBean對(duì)象;否則,如果這個(gè)Bean對(duì)象不是FactoryBean的話,就直接返回;如果是FactoryBean,那么就調(diào)用FactoryBean的getObject()返回目標(biāo)對(duì)象。

到此為此,spring是如何創(chuàng)建Bean實(shí)例,以及在創(chuàng)建Bean實(shí)例過(guò)程中相關(guān)的擴(kuò)展點(diǎn)總結(jié)完畢。后續(xù)將總結(jié)spring是如何通過(guò)這些擴(kuò)展點(diǎn)實(shí)現(xiàn)AOP功能的。

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

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

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