Spring5.0源码学习系列之浅谈Bean创建过程(六)

Stella981
• 阅读 689

系列文章目录

提示:Spring源码学习系列博客专栏


文章目录


前言

提示:在上一章的学习中,我们对BeanFactory的创建过程有了一个熟悉,其实实际的操作不止创建BeanFactory,调用的过程也实现了将xml解析为Document对象,再转换成BeanDefinition(很重要,Spring的Bean),并注册到BeanFactory,接着本文带着疑问学习一下Spring中的Bean(BeanDefinition)是怎么创建实例出来的?


提示:以下是本篇文章正文内容,下面案例可供参考

一、BeanDefinition实例过程简介

上一章学习了obtainFreshBeanFactory这个方法,经过这个方法,xml配置信息已经转换成一个BeanDefinition,但是BeanDefinition还没实例,属性也没配置,只是配置信息被提取出来,而且注册到BeanFactory
Spring5.0源码学习系列之浅谈Bean创建过程(六)
在之前文章学习,我们知道了,Bean的实例完成是在finishBeanFactoryInitialization这一步,当然是针对非懒加载的单例bean,多例的情况,后面有时间再来学习
Spring5.0源码学习系列之浅谈Bean创建过程(六)

二、finishBeanFactoryInitialization实现

ok,有了前面的简单了解,可以开始学习finishBeanFactoryInitialization的创建过程:通过代码,一步步跟,看看BeanDefinition是怎么初始化的?bean属性是怎么填充的?

/**
 * Finish the initialization of this context's bean factory,
 * initializing all remaining singleton beans.
 */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
   
   
   
    // Initialize conversion service for this context.
    // 初始化ConversionService,这个bean用于将前端传过来的参数和后端的 controller 方法上的参数进行绑定
    if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
            beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
   
   
   
        beanFactory.setConversionService(
                beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
    }

    // Register a default embedded value resolver if no bean post-processor
    // (such as a PropertyPlaceholderConfigurer bean) registered any before:
    // at this point, primarily for resolution in annotation attribute values.
    if (!beanFactory.hasEmbeddedValueResolver()) {
   
   
   
        beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
    }

    // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
    // 先初始化LoadTimeWeaverAware 类型的Bean
    // AspectJ 的内容,IoC的源码学习,先跳过
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
   
   
   
        getBean(weaverAwareName);
    }

    // Stop using the temporary ClassLoader for type matching.
    beanFactory.setTempClassLoader(null);

    // Allow for caching all bean definition metadata, not expecting further changes.
    // 冻结配置,不让bean 定义解析、加载、注册
    beanFactory.freezeConfiguration();

    // Instantiate all remaining (non-lazy-init) singletons.
    // 实例所有非懒加载的单例Bean
    beanFactory.preInstantiateSingletons();
}

{@link org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons}

@Override
public void preInstantiateSingletons() throws BeansException {
   
   
   
    if (logger.isDebugEnabled()) {
   
   
   
        logger.debug("Pre-instantiating singletons in " + this);
    }

    // Iterate over a copy to allow for init methods which in turn register new bean definitions.
    // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
    // 获取beanName列表,this.beanDefinitionNames 保存了所有的 beanNames
    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

    // Trigger initialization of all non-lazy singleton beans...
    // 触发所有非懒加载的单例bean初始化操作(lazy-init=false)
    for (String beanName : beanNames) {
   
   
   
        // 合并rootBean中的配置, <bean id="a" class="a" parent="p" />
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        // 非抽象(abstract = false)、非懒加载(lazy-init=false)的单例Bean(scope=singleton)
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
   
   
   
            // 处理FactoryBean,注意对比BeanFactory和FactoryBean
            if (isFactoryBean(beanName)) {
   
   
   
                // factoryBean调用在beanName加载前缀符号‘&’
                // 为什么要加‘&’,应该是做下标记,不过在bean创建过程要进行转换,详情请看下文
                Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                if (bean instanceof FactoryBean) {
   
   
   
                    FactoryBean<?> factory = (FactoryBean<?>) bean;
                    boolean isEagerInit;
                    // FactoryBean是SmartFactoryBean 的基类
                    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
   
   
   
                        isEagerInit = AccessController.doPrivileged(
                                (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
                                getAccessControlContext());
                    }
                    else {
   
   
   
                        isEagerInit = (factory instanceof SmartFactoryBean &&
                                ((SmartFactoryBean<?>) factory).isEagerInit());
                    }
                    if (isEagerInit) {
   
   
   
                        getBean(beanName);
                    }
                }
            }
            else {
   
   
   
                // 普通的Bean,调这个方法进行实例,往下跟
                getBean(beanName);
            }
        }
    }

    // Trigger post-initialization callback for all applicable beans...
    // SmartInitializingSingleton 的基类在这里回调
    for (String beanName : beanNames) {
   
   
   
        Object singletonInstance = getSingleton(beanName);
        if (singletonInstance instanceof SmartInitializingSingleton) {
   
   
   
            SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
   
   
   
                AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
   
   
   
                    smartSingleton.afterSingletonsInstantiated();
                    return null;
                }, getAccessControlContext());
            }
            else {
   
   
   
                smartSingleton.afterSingletonsInstantiated();
            }
        }
    }
}

AbstractBeanFactory.java
{@link org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean}

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

{@link org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean}

/**
 * Return an instance, which may be shared or independent, of the specified bean.
 * @param name the name of the bean to retrieve
 * @param requiredType the required type of the bean to retrieve
 * @param args arguments to use when creating a bean instance using explicit arguments
 * (only applied when creating a new instance as opposed to retrieving an existing one)
 * @param typeCheckOnly whether the instance is obtained for a type check,
 * not for actual use
 * @return an instance of the bean
 * @throws BeansException if the bean could not be created
 */
@SuppressWarnings("unchecked")
protected <T> T doGetBean(
        String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
        throws BeansException {
   
   
   
    //  处理BeanName,前面说的FactoryBean带‘&’符号,要在这里进行转换
    String beanName = transformedBeanName(name);
    Object bean;

    // Eagerly check singleton cache for manually registered singletons.
    // 从map(singletonObjects)里获取单例bean,确定是否已经存在对应实例
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
   
   
   
        if (logger.isDebugEnabled()) {
   
   
   
            if (isSingletonCurrentlyInCreation(beanName)) {
   
   
   
                logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
                        "' that is not fully initialized yet - a consequence of a circular reference");
            }
            else {
   
   
   
                logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
            }
        }
        // 两种情况:普通的bean,直接从singletonObjects返回sharedInstance
        //如果是FactoryBean,返回其创建的对象实例
        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);
        }

        // Check if bean definition exists in this factory.
        // 检查BeanFactory是否存在这个BeanDefinition
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
   
   
   
            // Not found -> check parent.
            // 当前容器找不到BeanDefinition,去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.
                // 返回parent容器的查询结果
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            }
            else {
   
   
   
                // No args -> delegate to standard getBean method.
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
        }

        if (!typeCheckOnly) {
   
   
   
            //typeCheckOnly为false的情况,将beanName放在一个alreadyCreated的集合
            markBeanAsCreated(beanName);
        }

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

            // Guarantee initialization of beans that the current bean depends on.
            // 校验是否配置了 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.
            // 单例的Bean
            if (mbd.isSingleton()) {
   
   
   
                sharedInstance = getSingleton(beanName, () -> {
   
   
   
                    try {
   
   
   
                        // 创建单例bean
                        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);
            }
            // 多例的Bean,scope = protoType
            else if (mbd.isPrototype()) {
   
   
   
                // It's a prototype -> create a new instance.
                Object prototypeInstance = null;
                try {
   
   
   
                    beforePrototypeCreation(beanName);
                     // 执行多例Bean创建
                    prototypeInstance = createBean(beanName, mbd, args);
                }
                finally {
   
   
   
                    afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            }
            // 如果不是单例bean也不是多例的bean,委托给对应的实现类
            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 {
   
   
   
                            // 执行bean创建
                            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;
        }
    }

    // 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.isDebugEnabled()) {
   
   
   
                logger.debug("Failed to convert bean '" + name + "' to required type '" +
                        ClassUtils.getQualifiedName(requiredType) + "'", ex);
            }
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        }
    }
    return (T) bean;
}

补充前面说的FactoryBean带‘&’符号问题可以在transformedBeanName看到原因
{@link org.springframework.beans.factory.support.AbstractBeanFactory#transformedBeanName}

/**
 * Return the bean name, stripping out the factory dereference prefix if necessary,
 * and resolving aliases to canonical names.
 * @param name the user-specified name
 * @return the transformed bean name
 */
protected String transformedBeanName(String name) {
   
   
   
    // 往下跟
    return canonicalName(BeanFactoryUtils.transformedBeanName(name));
}


/**
 * Return the actual bean name, stripping out the factory dereference
 * prefix (if any, also stripping repeated factory prefixes if found).
 * @param name the name of the bean
 * @return the transformed name
 * @see BeanFactory#FACTORY_BEAN_PREFIX
 */
public static String transformedBeanName(String name) {
   
   
   
    Assert.notNull(name, "'name' must not be null");
    String beanName = name;
    // FactoryBean的beanName是带‘&’的
    while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
   
   
   
        beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
    }
    return beanName;
}

{@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean}

/**
 * Central method of this class: creates a bean instance,
 * populates the bean instance, applies post-processors, etc.
 * @see #doCreateBean
 */
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable 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.
    // ClassLoader加载BeanDefinition 
    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
   
   
   
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    }

    // Prepare method overrides.
    // 处理方法覆盖
    //  todo 涉及bean 定义中的 <lookup-method />  和 <replaced-method />,先放过
    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.
        // todo 让InstantiationAwareBeanPostProcessor这个后置处理器有机会返回一个代理的实例,这个ioc源码学习先放过
        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 {
   
   
   
        // 重头戏,doCreateBean是实践执行bean创建的
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isDebugEnabled()) {
   
   
   
            logger.debug("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);
    }
}

继续跟doCreateBean

/**
 * 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(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
        throws BeanCreationException {
   
   
   

    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
   
   
   
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    // 不是FactoryBean的情况
    if (instanceWrapper == null) {
   
   
   
        // 创建Bean实例,但是还没设置属性
        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.
    // 涉及到MergedBeanDefinitionPostProcessor,先跳过 todo
    synchronized (mbd.postProcessingLock) {
   
   
   
        if (!mbd.postProcessed) {
   
   
   
            try {
   
   
   
                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.
    // 循环依赖的问题,先跳过 todo
    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, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
   
   
   
        // 关键一步,Bean属性填充
        populateBean(beanName, mbd, instanceWrapper);
        // 调用初始化方法,应用BeanPostProcess后置处理器
        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 {
   
   
   
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }
    catch (BeanDefinitionValidationException ex) {
   
   
   
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }

    return exposedObject;
}

看一下关键的createBeanInstance方法,这是创建bean实例的方法:

/**
 * Create a new instance for the specified bean, using an appropriate instantiation strategy:
 * factory method, constructor autowiring, or simple instantiation.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @param args explicit arguments to use for constructor or factory method invocation
 * @return a BeanWrapper for the new instance
 * @see #obtainFromSupplier
 * @see #instantiateUsingFactoryMethod
 * @see #autowireConstructor
 * @see #instantiateBean
 */
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
   
   
   
    // Make sure bean class is actually resolved at this point.
    // 确保classloader加载了此bean class
    Class<?> beanClass = resolveBeanClass(mbd, beanName);
    // 校验这个bean权限是否是public的
    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());
    }

    Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
    if (instanceSupplier != null) {
   
   
   
        return obtainFromSupplier(instanceSupplier, beanName);
    }

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

    // Candidate constructors for autowiring?
    // 判断是否采用有参构造函数
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null || mbd.getResolvedAutowireMode() == 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);
}

跳最简单的无参构造函数注入方法instantiateBean

/**
 * Instantiate the given bean using its default constructor.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @return a BeanWrapper for the new instance
 */
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
   
   
   
    try {
   
   
   
        Object beanInstance;
        if (System.getSecurityManager() != null) {
   
   
   
            beanInstance = AccessController.doPrivileged(
                    (PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
                    getAccessControlContext());
        }
        else {
   
   
   
            // 重点,实例过程
            beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
        }
        // BeanWrapper封装一下,返回
        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        initBeanWrapper(bw);
        return bw;
    }
    catch (Throwable ex) {
   
   
   
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
}

{@link org.springframework.beans.factory.support.SimpleInstantiationStrategy#instantiate}

@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
   
   
   
    // Don't override the class with CGLIB if no overrides.
    // 不存在方法覆写的情况,利用java的反射(JDK API)就能实现实例,方法覆写详情参考lookup-method 和 replaced-method
    if (!bd.hasMethodOverrides()) {
   
   
   
        Constructor<?> constructorToUse;
        synchronized (bd.constructorArgumentLock) {
   
   
   
            constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
            if (constructorToUse == null) {
   
   
   
                final Class<?> clazz = bd.getBeanClass();
                if (clazz.isInterface()) {
   
   
   
                    throw new BeanInstantiationException(clazz, "Specified class is an interface");
                }
                try {
   
   
   
                    if (System.getSecurityManager() != null) {
   
   
   
                        constructorToUse = AccessController.doPrivileged(
                                (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
                    }
                    else {
   
   
   
                        constructorToUse = clazz.getDeclaredConstructor();
                    }
                    bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                }
                catch (Throwable ex) {
   
   
   
                    throw new BeanInstantiationException(clazz, "No default constructor found", ex);
                }
            }
        }
        // 调用BeanUtils对构造方法进行实例
        return BeanUtils.instantiateClass(constructorToUse);
    }
    else {
   
   
   
        // Must generate CGLIB subclass.
        // 存在方法覆写的情况:SimpleInstantiationStrategy并没有提供实例化支持(JDK不支持),
        // 只能通过动态代理CGLIB实现,这是一个模板方法,给子类继承实现
        return instantiateWithMethodInjection(bd, beanName, owner);
    }
}

ok,前面是对bean实例过程的描述,接着继续跟一个关键点,Bean属性的填充,代码往上翻,找到{@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean}找到代码populateBean(beanName, mbd, instanceWrapper);

/**
 * Populate the bean instance in the given BeanWrapper with the property values
 * from the bean definition.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @param bw the BeanWrapper with bean instance
 */
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
   
   
   
    if (bw == null) {
   
   
   
        // bean是否有属性
        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.
    // 这个校验有点看不太懂 先跳过 todo
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
   
   
   
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
   
   
   
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
   
   
   
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                // 返回false,代表不需要进行后续的属性设值,也不需要调用后置处理器
                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.
        // 通过beanname找到属性值
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
   
   
   
            autowireByName(beanName, mbd, bw, newPvs);
        }
        // Add property values based on autowire by type if applicable.
        // 通用类型装配
        if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
   
   
   
            autowireByType(beanName, mbd, bw, newPvs);
        }
        pvs = newPvs;
    }

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

    if (hasInstAwareBpps || needsDepCheck) {
   
   
   
        if (pvs == null) {
   
   
   
            pvs = mbd.getPropertyValues();
        }
        PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        if (hasInstAwareBpps) {
   
   
   
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
   
   
   
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
   
   
   
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    // 后置处理器的内容,很重要的方面,不过内容比较多,先跳过
                    pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvs == null) {
   
   
   
                        return;
                    }
                }
            }
        }
        if (needsDepCheck) {
   
   
   
            checkDependencies(beanName, mbd, filteredPds, pvs);
        }
    }

    if (pvs != null) {
   
   
   
        //设置 bean 实例的属性值
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
}

归纳

提示:这里对文章进行归纳:ok,本文对BeanDefinition的实例过程进行简单的学习,Spring源码比较复杂,需要慢慢积累,才能对整个框架有很好的理解,这款框架有一个很值得学习的地方是很好地做到的面向接口编程,很多地方也用到了模板方法设计模式,工厂模式,等等,很好地应用了设计模式,针对BeanDefinition创建的过程,都有提供一些接口给子类拓展,框架就显得灵活,可拓展

本文同步分享在 博客“smileNicky”(CSDN)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Stella981 Stella981
3年前
Docker 部署SpringBoot项目不香吗?
  公众号改版后文章乱序推荐,希望你可以点击上方“Java进阶架构师”,点击右上角,将我们设为★“星标”!这样才不会错过每日进阶架构文章呀。  !(http://dingyue.ws.126.net/2020/0920/b00fbfc7j00qgy5xy002kd200qo00hsg00it00cj.jpg)  2
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这