美文网首页
Springboot 2.X启动原理分析

Springboot 2.X启动原理分析

作者: 不羁之后_ | 来源:发表于2019-08-01 14:27 被阅读0次

调用SpringApplication.run方法

/**
 * Created by dwz on 2019/7/31.
 */
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.youyou")
public class SpringbootStart {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootStart.class);
    }
}
run方法

对run方法总结如下:
1.获取创建SpringApplicationRunListener
2.创建参数,配置Enviroment
3.创建ApplicationContext
4.初始化ApplicationContext,加载Enviroment
5.refresh,加载各种bean
6.由 SpringApplicationRunListener 来发出 running 消息,告知程序已运行起来了

下面对refresh方法总结:

    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // 1.刷新前准备工作,包括设置启动时间,是否激活标识位,初始化属性源(property source)配置
            prepareRefresh();
            // 2.创建beanFactory
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            //3.准备创建好的beanFactory(给beanFactory设置ClassLoader,注册AOP相关的一些东西,注册环境相关的一些bean
            prepareBeanFactory(beanFactory);
            try {
                //4. 模板方法,为容器某些子类扩展功能所用(工厂后处理器)这里可以参考BeanFactoryPostProcessor接口的postProcessBeanFactory方法
                postProcessBeanFactory(beanFactory);
                //5.调用所有BeanFactoryPostProcessor注册为Bean
                invokeBeanFactoryPostProcessors(beanFactory);
                //6.注册所有实现了BeanPostProcessor接口的Bean
                registerBeanPostProcessors(beanFactory);
                // 7.初始化MessageSource,和国际化相关
                initMessageSource();
                // 8.初始化容器事件传播器
                initApplicationEventMulticaster();
                // 9.调用容器子类某些特殊Bean的初始化,模板方法
                onRefresh();
                // 10.为事件传播器注册监听器
                registerListeners();
                // 11.初始化所有剩余的bean(普通bean)
                finishBeanFactoryInitialization(beanFactory);
                // 12.初始化容器的生命周期事件处理器,并发布容器的生命周期事件
                finishRefresh();
            }
            catch (BeansException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
                }
                // 13.销毁已创建的bean
                destroyBeans();
                // 14.重置`active`标志
                cancelRefresh(ex);
                throw ex;
            }
            finally {
                                //重置一些缓存
                resetCommonCaches();
            }
        }
    }

1.创建beanFactory
2.调用所有BeanFactoryPostProcessor注册为Bean
3.初始化MessageSource,和国际化相关
4.初始化所有剩余的bean(普通bean)
整体流程图如下:


image.png

相关文章

网友评论

      本文标题:Springboot 2.X启动原理分析

      本文链接:https://www.haomeiwen.com/subject/cvetdctx.html