Bean到底是咋生下来的?

老子终于更新了,哈哈哈哈
上回书咱们说道,bean的生成全靠BeanDefinition,但是BeanDefinition里面仅仅只有bean的结构内容,而它还要经过一系列的组装,再最终完成后可能跟当初定义的bean大相径庭,就好比我和思聪在上帝那都定义为人,但是出生的时候....默默流下了泪水。这里,我们就围绕着bean在生产过程中遇到的一些事件(比实例化前后处理器等)来展开剖析。

一. doGetBean

doGetBean是在AbstractBeanFactory容器中定义的方法,我们就拿他来开刀。

protected  T doGetBean(final String name, @Nullable final Class requiredType,
            @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

        // 这里主要是处理别名或者FactoryBean的名字
        final String beanName = transformedBeanName(name);
        Object bean;

        // 先从三级缓存中尝试获取bean,详情见下文
        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 + "'");
                }
            }
            // 这个主要对FactoryBean做处理,如果sharedInstance 是一个FactoryBean,那它将返回FactoryBean中所创建的实例
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }

        else {

            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            //先委托给父BeanFactory去看看能否创建出实例
            BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                String nameToLookup = originalBeanName(name);
                if (parentBeanFactory instanceof AbstractBeanFactory) {
                    return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                            nameToLookup, requiredType, args, typeCheckOnly);
                }
                else if (args != null) {
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else if (requiredType != null) {
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
                else {
                    return (T) parentBeanFactory.getBean(nameToLookup);
                }
            }

            //标记Bean为正在创建中的一个状态
            if (!typeCheckOnly) {
                markBeanAsCreated(beanName);
            }

            try {
                //如果此bean对应的BeanDefinition有双亲,则需要合并BeanDefinition中的内容
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);

                // 这里获取XML中显示指定的depends-on的依赖,并递归获取这些依赖Bean的实例
                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);
                        }
                    }
                }

                // 我们主要分析单例Bean的生成
                if (mbd.isSingleton()) {
                    // addSingleton里面调用的核心是createBean,在createBean方法创建完bean之后会把bean加入一级缓存并删除二三级的缓存
                    sharedInstance = getSingleton(beanName, () -> {
                        try {
                            return createBean(beanName, mbd, args);
                        }
                        catch (BeansException ex) {
                            destroySingleton(beanName);
                            throw ex;
                        }
                    });
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }

                //忽略部分代码
                .....

                }
            }
            catch (BeansException ex) {
                cleanupAfterBeanCreationFailure(beanName);
                throw ex;
            }
        }

        //忽略部分代码
        .....

        return (T) bean;
    }
  • getSingleton

singletonObject : 第一级缓存,存放完整的Bean
earlySingletonObjects: 第二级缓存,存放不完整的Bean
singletonFactories: 第三级缓存,存放Bean工厂
singletonObject 是一个 ConcurrentHashMap,而earlySingletonObjects和singletonFactories是一个HashMap,看下这个方法的实现就知道为啥。

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        //肯定要先看看一级缓存在不在
        Object singletonObject = this.singletonObjects.get(beanName);
        //该Bean不存在或者还在创建中
        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) {
                        //如果从Bean工厂中拿到bean则存入二级缓存并删除三级缓存
                        singletonObject = singletonFactory.getObject();
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        this.singletonFactories.remove(beanName);
                    }
                }
            }
        }
        return singletonObject;
    }

二. createBean

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;

        // 这里主要是加载bean的Class
        Class resolvedClass = resolveBeanClass(mbd, beanName);
        if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
            mbdToUse = new RootBeanDefinition(mbd);
            mbdToUse.setBeanClass(resolvedClass);
        }

        // 这里准备需要重写的方法,注意这里不是@override标记的方法,而是在XML中显示指明要替换的方法,
        try {
            mbdToUse.prepareMethodOverrides();
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                    beanName, "Validation of method overrides failed", ex);
        }

        try {
            //这里就精髓了,如果用户自定义了bean的生成方式,则直接return,返回不会让doCreateBean方法执行,详情看下文
            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 {
            //这里是bean生成的核心,详情看下文
            Object beanInstance = doCreateBean(beanName, mbdToUse, args);
            if (logger.isTraceEnabled()) {
                logger.trace("Finished creating instance of bean '" + beanName + "'");
            }
            return beanInstance;
        }
        catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {

            throw ex;
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
        }
    }
  • resolveBeforeInstantiation

在bean生成的时候,Spring会加载很多BeanPostProcessors来对bean的生成过程做一个增强。
而InstantiationAwareBeanPostProcessor是众多BeanPostProcessor子类的其中之一,它里面有5个关键的方法:

postProcessBeforeInstantiation:Bean实例化的前置方法
postProcessAfterInstantiation:Bean实例化的后置方法
postProcessBeforeInitialization:Bean初始化的前置方法
postProcessAfterInitialization:Bean初始化的后置方法
postProcessProperties:辅助依赖注入

applyBeanPostProcessorsBeforeInstantiation的目的就是执行Bean实例化的前置方法。假如Bean实例化的前置方法中生成了用户自定义的Bean,那就会直接执行Bean初始化的后置方法,之后将生成的Bean直接返回给用户,而不交由spring的doCreateBean来创建Bean。

    protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
        Object bean = null;
        if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
            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;
    }

二.doCreateBean

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

        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            //尝试从缓存中获取factoryBean(就当是我们将要获取的bean的包装bean实例)
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        if (instanceWrapper == null) {
            //尝试使用工厂方法、有参构造函数、无参构造函数去实例化一个bean
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        final Object bean = instanceWrapper.getWrappedInstance();
        Class beanType = instanceWrapper.getWrappedClass();
        if (beanType != NullBean.class) {
            mbd.resolvedTargetType = beanType;
        }

        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    //这里是为依赖注入做准备,主要是AutowiredAnnotationBeanPostProcessor起作用
                    //这个PostProcessor会解析@autowired和@value注解并把标记的属性封装成InjectionMetadata元数据加入缓存,
                    //之后在populateBean中会调用此PostProcessor实例化后置方法并根据这些元数据去进行属性注入
                    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                }
                catch (Throwable ex) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            "Post-processing of merged bean definition failed", ex);
                }
                mbd.postProcessed = true;
            }
        }

        
        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");
            }
            // addSingletonFactory就是将bean加入第三级缓存
            // getEarlyBeanReference的实现是在AbstractAutoProxyCreator这个类里面,里面是实现AOP和创建代理对象的核心
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }

        Object exposedObject = bean;
        try {
            // 属性注入的核心方法,下文会讲到
            populateBean(beanName, mbd, instanceWrapper);
            // 1.处理继承了BeanNameAware、BeanClassLoaderAware、BeanFactoryAware接口的bean并注入这些值
            // 2.执bean初始化前置方法
            // 3.执bean初始化方法
            // 4.执bean初始化后置方法
            exposedObject = initializeBean(beanName, exposedObject, mbd);
        }
        //忽略部分代码
        .....

        
    }
  • populateBean
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
        //忽略部分代码
        .....

        // 这里是执行实例化的后置方法,这个方法返回值为boolean,可以控制能否继续执行后面有关依赖注入的代码
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                        return;
                    }
                }
            }
        }

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

        //这里是处理xml中某些Bean显示指定BY_NAME或BY_TYPE的方式来注入
        int resolvedAutowireMode = mbd.getResolvedAutowireMode();
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
            MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
            if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
                autowireByName(beanName, mbd, bw, newPvs);
            }
            if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
                autowireByType(beanName, mbd, bw, newPvs);
            }
            pvs = newPvs;
        }

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

        //下面这一块就是注入的核心流程了,主要还是依赖于AutowiredAnnotationBeanPostProcessor,会在Bean列表中找出最符合的bean注入,这个有时间再细细撸
        PropertyDescriptor[] filteredPds = null;
        if (hasInstAwareBpps) {
            if (pvs == null) {
                pvs = mbd.getPropertyValues();
            }
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                    if (pvsToUse == null) {
                        if (filteredPds == null) {
                            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                        }
                        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生成经历的一些过程(缩进太多我直接贴图了)

image.png

你可能感兴趣的:(Bean到底是咋生下来的?)