SpringBoot2.2.6启动run方法之refreshContext

SpringBoot2.2.6启动run方法之refreshContext

前言

此系列是针对springboot的启动,旨在于和大家一起来看看springboot启动的过程中到底做了一些什么事。文中有不清楚或错误的地方
欢迎留言指正。

源码解读进度

首先我们的源码阅读进度

public ConfigurableApplicationContext run(String... args) {
    // 用于记录启动时间
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    // 声明Spring上下文
    ConfigurableApplicationContext context = null;
    // 声明启动错误回掉
    Collection exceptionReporters = new ArrayList<>();
    // 设置jdk系统属性java.awt.headless,默认情况为true即开启
    configureHeadlessProperty();
    // 装饰者模式创建启动监听器(EventPublishingRunListener实例)
    SpringApplicationRunListeners listeners = getRunListeners(args);
    // 触发ApplicationStartingEvent事件,包括转换器的初始化
    listeners.starting();
    try {
        // 参数封装,也就是在命令行下启动应用带的参数
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        // 准备环境:1、加载外部化配置的资源到environment;2、触发ApplicationEnvironmentPreparedEvent事件
        ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
        配置spring.beaninfo.ignore,并添加到名叫systemProperties的PropertySource中;默认为true即开启
        configureIgnoreBeanInfo(environment);
        打印banner图
        Banner printedBanner = printBanner(environment);
        创建应用上下文,这是本文重点
        context = createApplicationContext();
        exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                new Class[] { ConfigurableApplicationContext.class }, context);
        // applicationcontext初始化
        prepareContext(context, environment, listeners, applicationArguments, printedBanner);
        // applicationcontext刷新,bean的创建
        refreshContext(context);
        afterRefresh(context, applicationArguments);
        stopWatch.stop();
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
        }
        listeners.started(context);
        callRunners(context, applicationArguments);
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, listeners);
        throw new IllegalStateException(ex);
    }
    try {
        listeners.running(context);
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, null);
        throw new IllegalStateException(ex);
    }
    return context;
}

先看一下refreshContext方法

private void refreshContext(ConfigurableApplicationContext context) {
    refresh(context);
    if (this.registerShutdownHook) {
        try {
        // 调用方法Runtime.getRuntime().addShutdownHook(this.shutdownHook);注册一个hook,接收到关闭信号的时候清理内存
            context.registerShutdownHook();
        }
        catch (AccessControlException ex) {
            // Not allowed in some environments.
        }
    }
}

可以看到,refreshContext方法之做了两部操作,1. refresh 2. 添加一个ShutdownHook

解析一下refreshContext方法里面的refresh(context)做了什么事情

protected void refresh(ApplicationContext applicationContext) {
    // 验证applicationContext是否是一个AbstractApplicationContext
    Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
    // 强转applicationContext为AbstractApplicationContext,并调用AbstractApplicationContext的refresh()
    ((AbstractApplicationContext) applicationContext).refresh();
}

继续看一下AbstractApplicationContext的refresh()方法都做了什么?
debug可以看到,refresh首先调用的是子类ServletWebServerApplicationContext重写的refresh方法

@Override
public final void refresh() throws BeansException, IllegalStateException {
    try {
        // 调用AbstractApplicationContext的refresh方法
        super.refresh();
    }
    catch (RuntimeException ex) {
        // 如果发生异常,调用WebServer的stop方法,关闭tomcat
        stopAndReleaseWebServer();
        throw ex;
    }
}

然后调用父类AbstractApplicationContext的refresh方法

@Override
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // 1. 准备工作
        prepareRefresh();
        // 2. 获取BeanFactory
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
        // 3. 初始化beanFactory
        prepareBeanFactory(beanFactory);
        try {
            // 添加一个获取ServletContext和ServletConfig的后置处理器,并忽略ServletContextAware的自动装配
            // 用来添加web特有的作用域scope,例如REQUEST、SESSION
            postProcessBeanFactory(beanFactory);
            // 执行BeanFactoryPostProcessor并注册到applicationcontext
            invokeBeanFactoryPostProcessors(beanFactory);
            // 注册BeanPostProcessor到applicationcontext
            registerBeanPostProcessors(beanFactory);
            // 初始化一个DelegatingMessageSource到beanfactory中
            initMessageSource();
            // 初始化一个带beanfactory的ApplicationEventMulticaster
            initApplicationEventMulticaster();
            // 父类的onRefresh之初始化了ThemeSource,createWebServer方法创建一个tomcatwebserver,初始化参数
            onRefresh();
            // 为ApplicationEventMulticaster注册applicationcontext中已有的ApplicationListener
            // 并从beanfactory中获取实现ApplicationListener的bean名称,注册到ApplicationEventMulticaster
            // 然后调用一些earlyApplicationEvents事件
            registerListeners();
            // 4.完成BeanFactory的初始化,主要是调用了beanFactory的preInstantiateSingletons方法
            finishBeanFactoryInitialization(beanFactory);
            finishRefresh();
        }
        catch (BeansException ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Exception encountered during context initialization - " +
                        "cancelling refresh attempt: " + ex);
            }
            destroyBeans();
            cancelRefresh(ex);
            throw ex;
        }
        finally {
            resetCommonCaches();
        }
    }
}

下面分析一下每一步具体做了什么事情
1. prepareRefresh准备工作
首先会调用AnnotationConfigServletWebServerApplicationContext的重写方法

@Override
protected void prepareRefresh() {
    // ClassPathBeanDefinitionScanner清除缓存
    this.scanner.clearCache();
    // 调用AbstractApplicationContext的prepareRefresh
    super.prepareRefresh();
}

然后看一下AbstractApplicationContext的prepareRefresh

protected void prepareRefresh() {
    // 记录当前时间
    this.startupDate = System.currentTimeMillis();
    // 初始化closed 
    this.closed.set(false);
    // 初始化active
    this.active.set(true);
    if (logger.isDebugEnabled()) {
        if (logger.isTraceEnabled()) {
            logger.trace("Refreshing " + this);
        }
        else {
            logger.debug("Refreshing " + getDisplayName());
        }
    }
    // 初始化环境变量
    initPropertySources();
    // 验证是否存在没有设置的环境变量
    getEnvironment().validateRequiredProperties();
    // 初始化一个早期的ApplicationListener列表,并把当前的ApplicationListener赋值
    if (this.earlyApplicationListeners == null) {
        this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
    }
    else {
        // Reset local application listeners to pre-refresh state.
        this.applicationListeners.clear();
        this.applicationListeners.addAll(this.earlyApplicationListeners);
    }
    // 初始化一个早期的ApplicationEvent容器,当新的multicaster可用时发布出去
    this.earlyApplicationEvents = new LinkedHashSet<>();
}

2. obtainFreshBeanFactory
该方法主要是刷新BeanFactory

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    // 刷新beanfactory
    refreshBeanFactory();
    // 返回刷新后的beanfactory
    return getBeanFactory();
}

下面看一下beanfactory是如何刷新的

@Override
protected final void refreshBeanFactory() throws IllegalStateException {
    // 如果已经刷新过了,抛出异常
    if (!this.refreshed.compareAndSet(false, true)) {
        throw new IllegalStateException(
                "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
    }
    // 为beanFactory指定一个序列化id,使用的是server.name
    this.beanFactory.setSerializationId(getId());
}

3. prepareBeanFactory

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // 设置classloader
    beanFactory.setBeanClassLoader(getClassLoader());
    // 设置beanFactory的表达式语言处理器
    beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    // 为beanFactory增加了一个默认的propertyEditor,这个主要是对bean的属性等设置管理的一个工具
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
    // 添加一个后置处理器,为实现EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware
    // 、MessageSourceAware、ApplicationContextAware等接口的bean设置属性
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    // 设置以下接口忽略自动装配功能
    beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
    beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
    beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
    beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
    // 为以下的bean指定类型
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);
    // 添加ApplicationListener探测器,实现ApplicationListener的bean会添加到applicationcontext中
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
    // 注册bean
    // Detect a LoadTimeWeaver and prepare for weaving, if found.
    if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        // Set a temporary ClassLoader for type matching.
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
    // Register default environment beans.
    if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
    }
    if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
    }
    if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
    }
}

4. preInstantiateSingletons对bean对象实例化

public void preInstantiateSingletons() throws BeansException {
    if (logger.isTraceEnabled()) {
        logger.trace("Pre-instantiating singletons in " + this);
    }
    // 根据beanDefinitionNames的数量,创建一个beanName副本
    List beanNames = new ArrayList<>(this.beanDefinitionNames);
    // 循环实例化所有的非lazy加载的bean
    for (String beanName : beanNames) {
        // 获取合并后的BeanDefinition,BeanDefinition有变动,getMergedLocalBeanDefinition都会重新合并
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        // 非抽象、单例、非懒加载的Bean处理
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            // 判断是否是一个FactoryBean
            if (isFactoryBean(beanName)) {
                // FactoryBean的name前面添加&,初始化FactoryBean
                Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                ...
            }
            else {
                // 初始化非FactoryBean
                getBean(beanName);
            }
        }
    }
    // 循环所有的bean,判断是否实现了SmartInitializingSingleton接口,如果实现了该接口,就会调用afterSingletonsInstantiated方法
    // 用来对bean进行初始化操作
    for (String beanName : beanNames) {
        Object singletonInstance = getSingleton(beanName);
        if (singletonInstance instanceof SmartInitializingSingleton) {
            final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged((PrivilegedAction) () -> {
                    smartSingleton.afterSingletonsInstantiated();
                    return null;
                }, getAccessControlContext());
            }
            else {
                smartSingleton.afterSingletonsInstantiated();
            }
        }
    }
}
 
 

下面我们具体分析一下getBean方法做了什么事情

// FactoryBean和普通bean都是调用的该方法
public Object getBean(String name) throws BeansException {
    return doGetBean(name, null, null, false);
}
// name:如果FactoryBean前面加& ; requiredType=null; args =null;typeCheckOnly=false
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;
    // 查询一下singletonObjects中,该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,是的话调用FactoryBean的getObject方法获取真正的Bean
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }
    else {
        // 异常情况,暂不分析
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }
        // 暂不分析存在ParentBeanFactory的情况
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            ...
        }
        if (!typeCheckOnly) {
            // 1.将beanName添加到alreadyCreated中 2.同时修改MergedBeanDefinition的stale状态,下次获取MergedBeanDefinition的时候重新创建
            // 防止创建过程中原数据修改后没有及时更新
            markBeanAsCreated(beanName);
        }
        // 下面是Bean的创建过程
        try {
            // 重新获取MergedBeanDefinition
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            // 判断是否是Abstract,如果是就抛出异常
            checkMergedBeanDefinition(mbd, beanName, args);
            // DependsOn注解,查看该Bean是否有需要优先加载的bean
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dep : dependsOn) {
                    // 判断是否有因为DependsOn导致的循环依赖
                    if (isDependent(beanName, dep)) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                    }
                    // 注册依赖关系
                    registerDependentBean(dep, beanName);
                    try {
                        // 递归调用,先初始化依赖的bean
                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                    }
                }
            }
            // 创建单例Bean
            if (mbd.isSingleton()) {
                // 实例创建
                sharedInstance = getSingleton(beanName, () -> {
                    try {
                        return createBean(beanName, mbd, args);
                    }
                    catch (BeansException ex) {
                        // Explicitly remove instance from singleton cache: It might have been put there
                        // eagerly by the creation process, to allow for circular reference resolution.
                        // Also remove any beans that received a temporary reference to the bean.
                        destroySingleton(beanName);
                        throw ex;
                    }
                });
                  // 如果是一个FactoryBean,调用FactoryBean方法创建Bean对象
                  // 这时候,bean已经创建出来了
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            }
            else if (mbd.isPrototype()) {
                Object prototypeInstance = null;
                try {
                    beforePrototypeCreation(beanName);
                    prototypeInstance = createBean(beanName, mbd, args);
                }
                finally {
                    afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            }
            else {
                String scopeName = mbd.getScope();
                final Scope scope = this.scopes.get(scopeName);
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                }
                try {
                    Object scopedInstance = scope.get(beanName, () -> {
                        beforePrototypeCreation(beanName);
                        try {
                            return createBean(beanName, mbd, args);
                        }
                        finally {
                            afterPrototypeCreation(beanName);
                        }
                    });
                    bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                }
                catch (IllegalStateException ex) {
                    throw new BeanCreationException(beanName,
                            "Scope '" + scopeName + "' is not active for the current thread; consider " +
                            "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                            ex);
                }
            }
        }
        catch (BeansException ex) {
            cleanupAfterBeanCreationFailure(beanName);
            throw ex;
        }
    }
    // 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;
}

分析一下getSingleton做了什么事情

public Object getSingleton(String beanName, ObjectFactory singletonFactory) {
    Assert.notNull(beanName, "Bean name must not be null");
    synchronized (this.singletonObjects) {
        // 再次判断是否创建
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null) {
            // 判断是否是不允许创建单例对象
            if (this.singletonsCurrentlyInDestruction) {
                throw new BeanCreationNotAllowedException(beanName,
                        "Singleton bean creation not allowed while 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 + "'");
            }
            // 根据beanName判断是否是排除创建的Bean,并向singletonsCurrentlyInCreation中添加该beanName
            beforeSingletonCreation(beanName);
            boolean newSingleton = false;
            boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
            if (recordSuppressedExceptions) {
                this.suppressedExceptions = new LinkedHashSet<>();
            }
            try {
                调用singletonFactory的getObject方法获取实例
                singletonObject = singletonFactory.getObject();
                newSingleton = true;
            }
            catch (IllegalStateException ex) {
                // Has the singleton object implicitly appeared in the meantime ->
                // if yes, proceed with it since the exception indicates that state.
                singletonObject = this.singletonObjects.get(beanName);
                if (singletonObject == null) {
                    throw ex;
                }
            }
            catch (BeanCreationException ex) {
                if (recordSuppressedExceptions) {
                    for (Exception suppressedException : this.suppressedExceptions) {
                        ex.addRelatedCause(suppressedException);
                    }
                }
                throw ex;
            }
            finally {
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = null;
                }
                // 向singletonsCurrentlyInCreation中添加beanName
                afterSingletonCreation(beanName);
            }
            if (newSingleton) {
                // 向singletonObjects中添加
                // singletonFactories清除
                // earlySingletonObjects清除
                // registeredSingletons添加
                addSingleton(beanName, singletonObject);
            }
        }
        return singletonObject;
    }
}

singletonFactory.getObject();最后调用的是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;
    // 获取Class
    Class resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    }
    try {
        // 将重载方法标记为未重载
        mbdToUse.prepareMethodOverrides();
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                beanName, "Validation of method overrides failed", ex);
    }
    try {
        // 查询所有的后置处理器,判断是否是InstantiationAwareBeanPostProcessor,循环调用postProcessBeforeInstantiation方法
        // 可以实现该方法,自己创建Bean的实例
        // 如果postProcessBeforeInstantiation返回实例不为null,循环所有的后置处理器,调用postProcessAfterInitialization方法
        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 {
        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);
    }
}

下面看一下doCreateBean方法

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
            throws BeanCreationException {
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        // 清除FactoryBean创建时的缓存
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        // 调用构造器初始化,并包装成BeanWrapper对象
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    // 从BeanWrapper中获取Bean对象
    final Object bean = instanceWrapper.getWrappedInstance();
    // 获取Bean的class类型
    Class beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        mbd.resolvedTargetType = beanType;
    }
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                // 调用所有的MergedBeanDefinitionPostProcessor后置处理器的postProcessMergedBeanDefinition方法
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }
    // 是否是单例,允许解决循环引用,当前正在创建的bean
    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");
        }
        // singletonFactories添加beanname和singletonFactory
        // earlySingletonObjects移除beanname
        // registeredSingletons添加beanname
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }
    Object exposedObject = bean;
    try {
        // 循环所有的InstantiationAwareBeanPostProcessor后置处理器,调用postProcessProperties
        // 循环设置属性
        populateBean(beanName, mbd, instanceWrapper);
        // 处理BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
        // 调用所有后置处理器的postProcessBeforeInitialization方法
        // 调用init方法
        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) {
    // 先从singletonObjects中获取,如果获取不到从earlySingletonObjects中获取,如果还获取不到就从singletonFactories中获取
    // 上面代码已经添加过singletonFactories,调用getEarlyBeanReference(beanName, mbd, bean)获取bean早期对象,一般返回null
        Object earlySingletonReference = getSingleton(beanName, false);
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
            }
            else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                String[] dependentBeans = getDependentBeans(beanName);
                Set actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        actualDependentBeans.add(dependentBean);
                    }
                }
                if (!actualDependentBeans.isEmpty()) {
                    throw new BeanCurrentlyInCreationException(beanName,
                            "Bean with name '" + beanName + "' has been injected into other beans [" +
                            StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                            "] in its raw version as part of a circular reference, but has eventually been " +
                            "wrapped. This means that said other beans do not use the final version of the " +
                            "bean. This is often the result of over-eager type matching - consider using " +
                            "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
                }
            }
        }
    }
    try {
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }
    return exposedObject;
}

总结:doCreateBean方法主要是创建bean对象

你可能感兴趣的:(SpringBoot2.2.6启动run方法之refreshContext)