在 SpringBoot 启动流程中,主要的两个阶段是初始化 SpringApplication 对象以及 SpringApplication.run 方法执行的内容,今天主要细讲的是 SpringApplication.run 中的刷新容器 refreshContext 方法,refreshContext 的源码如下
refreshContext 方法主要是刷新容器,下面我们来看一下 refreshContext 的源码,点击 SpringApplication.run 方法的 refreshContext 方法
看到 refreshContext 的方法内容很简单,主要是调用 refresh 方法
继续点击 refresh 方法可以看到,Refresh the underlying {@link ApplicationContext}也就是刷新底层的 ApplicationContext
继续跟进去,这里要选择 AbstractApplicationContext
这里我们看一下 AbstractApplicationContext 的注释,注释内容
Abstract implementation of the {@link org.springframework.context.ApplicationContext} interface. Doesn’t mandate the type of storage used for configuration; simply implements common context functionality. Uses the Template Method design pattern,requiring concrete subclasses to implement abstract methods.翻译过来就是当前抽象类是 ApplicationContext 接口的抽象实现,不强制要求用于配置的存储类型;它只是实现了公共上下文功能,使用的是模板方法的设计模式,需要具体的子类来实现抽象方法。下面我们再来看 refresh 方法
refresh 方法主要是刷新应用程序上下文,这里主要涉及到准备刷新上下文,调用上下文注册为 bean 的工厂处理器,初始化上下文的消息源,初始化特定上下文子类中的其他特殊 bean,检查监听器 bean 并注册,最后发布相应的事件并销毁已经创建的单例及重置 active 标志,整体的注解我都直接加在源码中了
到这里 SpringBoot 启动流程中的 refreshContext 方法的主体源码内容已经讲解完了,后续我们继续深入来看 refresh 方法内部子方法的源码,敬请关注。