Spring boot源码深入学习(六) | 容器的创建,准备,刷新,启动

回顾

上一篇:Spring boot源码深入学习(五) | 准备环境时application配置文件的加载优先级
学习了prepareEnvironment准备环境:
1.初始化环境
2.配置环境
3.加载配置文件.通过ApplicationEnvironmentPreparedEvent事件发布,执行对应的监听器事件
4.绑定环境到SpringApplication
下面学习一下容器的创建,准备,刷新,启动。
首先看一看核心run方法流程回顾一下:

	public ConfigurableApplicationContext run(String... args) {
		// 实例化一个stopWatch,用于统计spring boot项目启动花费的时间
		StopWatch stopWatch = new StopWatch();
		// 开始计时
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		// exception reporter,统计异常信息
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
		// 设置 java.awt.headless 为true
		// Headless模式是系统的一种配置模式。在系统可能缺少显示设备、键盘或鼠标这些外设的情况下可以使用该模式。服务器不需要外设
		configureHeadlessProperty();
		// 【1】获取监听器
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting();
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(
					args);
			// 【2】准备环境
			ConfigurableEnvironment environment = prepareEnvironment(listeners,
					applicationArguments);
			// 配置spring.beaninfo.ignore属性,默认为true
			// 跳过对BeanInfo类的搜索(通常用于首先没有为应用程序中的bean定义此类的情况)
			configureIgnoreBeanInfo(environment);
			// 【3】控制台打印Banner
			Banner printedBanner = printBanner(environment);
			// 【4】创建容器,根据不同类型创建不同的容器
			context = createApplicationContext();
			// 【5】实例化异常报告期实例,用于记录启动过程中的错误。
			exceptionReporters = getSpringFactoriesInstances(
					SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);
			// 【6】准备容器,给刚刚创建的容器做一些初始化工作
			prepareContext(context, environment, listeners, applicationArguments,
					printedBanner);
			// 【7】刷新容器,这一步至关重要。后续再做解析
			refreshContext(context);
			// 【8】刷新容器后的一些操作,这里是空方法
			afterRefresh(context, applicationArguments);
			// 停止计时器
			stopWatch.stop();
			// 开启日志打印
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass)
						.logStarted(getApplicationLog(), stopWatch);
			}
			// 启动容器,加载所有bean实例
			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;
	}

创建容器createApplicationContext()

根据none,servlet,reactive三种类型创建不同的容器

	// 【4】创建容器,根据不同类型创建不同的容器
	context = createApplicationContext();
	protected ConfigurableApplicationContext createApplicationContext() {
		Class<?> contextClass = this.applicationContextClass;
		if (contextClass == null) {
			try {
				// 根据类型创建不同的容器,这里是SERVLET
				switch (this.webApplicationType) {
				case SERVLET:
					// AnnotationConfigServletWebServerApplicationContext
					contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
					break;
				case REACTIVE:
					contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
					break;
				default:
					contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
				}
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Unable create a default ApplicationContext, "
								+ "please specify an ApplicationContextClass",
						ex);
			}
		}
		return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
	}

准备容器prepareContext

	// 【6】准备容器,给刚刚创建的容器做一些初始化工作
	prepareContext(context, environment, listeners, applicationArguments,
					printedBanner);

【1】给容器设置环境

【2】根据情况对ApplicationContext做一些相关的后置处理

  • beanNameGenerator
  • resourceLoader
  • 添加转换器ConversionService

【3】执行之前SpringApplication的实例化时候加载的各个ApplicationContextInitializer的初始化方法
在这里插入图片描述

【4】执行各个监听器对应的事件,ApplicationContextInitializedEvent
在这里插入图片描述
【5】开启日志打印

【6】从context容器中获取beanFactory,并向beanFactory中注册一些单例bean

【7】获取启动类的参数
springApplicationArguments
springBootBanner

【8】加载启动类,注入到容器

【9】通知监听器容器准备就绪,发布
ApplicationPreparedEvent事件

	private void prepareContext(ConfigurableApplicationContext context,
			ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
			ApplicationArguments applicationArguments, Banner printedBanner) {
		// 【1】设置环境
		context.setEnvironment(environment);
		// 【2】根据情况对ApplicationContext做一些相关的后置处理
		// beanNameGenerator,resourceLoader或者添加转换器ConversionService
		postProcessApplicationContext(context);
		// 【3】执行之前SpringApplication的实例化时候加载的各个ApplicationContextInitializer的初始化方法
		applyInitializers(context);
		// 【4】执行各个监听器对应的事件,ApplicationContextInitializedEvent
		listeners.contextPrepared(context);
		// 【5】开启日志打印
		if (this.logStartupInfo) {
			logStartupInfo(context.getParent() == null);
			logStartupProfileInfo(context);
		}
		// 【6】从context容器中获取beanFactory,并向beanFactory中注册一些单例bean
		ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
		beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
		if (printedBanner != null) {
			beanFactory.registerSingleton("springBootBanner", printedBanner);
		}
		if (beanFactory instanceof DefaultListableBeanFactory) {
			((DefaultListableBeanFactory) beanFactory)
					.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
		}
		// 【7】获取启动类的参数
		Set<Object> sources = getAllSources();
		Assert.notEmpty(sources, "Sources must not be empty");
		// 【8】加载启动类,注入到容器
		load(context, sources.toArray(new Object[0]));
		// 【9】通知监听器容器准备就绪,发布ApplicationPreparedEvent事件
		listeners.contextLoaded(context);
	}

刷新容器refreshContext

到这里,就是spring的工作了。下面简要看一看spring如何处理容器。后续学习spring的时候详细深入学习。

	private void refreshContext(ConfigurableApplicationContext context) {
		// 刷新容器
		refresh(context);
		// 钩子函数,优雅的关闭ioc容器
		if (this.registerShutdownHook) {
			try {
				context.registerShutdownHook();
			}
			catch (AccessControlException ex) {
				// Not allowed in some environments.
			}
		}
	}

往下跟进核心方法,refresh方法

	@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// 容器刷新前的一些操作,设置启动时间,初始化PropertySources,校验requiredProperties
			prepareRefresh();

			// 初始化beanfactory,加载xml配置的bean定义
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// 准备上面初始化的beanfactory
			// 1.告诉内部bean工厂使用上下文的类加载器等
			// 2.使用上下文回调配置bean工厂
			// 添加ApplicationContextAwareProcessor处理器
			// 在依赖注入忽略实现*Aware的接口
			// 3.BeanFactory注册依赖
			// 4.检测LoadTimeWeaver并准备编织(如果找到)
			// 5.注册默认环境的bean
			prepareBeanFactory(beanFactory);

			try {
				// 子类处理自定义的BeanFactoryPostProcess
				postProcessBeanFactory(beanFactory);

				 // 激活各种BeanFactory处理器,包括BeanDefinitionRegistryBeanFactoryPostProcessor和普通的BeanFactoryPostProcessor
				 // 执行对应的postProcessBeanDefinitionRegistry方法 和  postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(beanFactory);
 	
 	            // 注册所有的BeanPostProcessor。这里只是注册,在实例化的时候执行对应的方法
            	registerBeanPostProcessors(beanFactory);

				// 初始化容器的资源文件
				initMessageSource();

				// 初始化事件广播
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// 注册所有的Listener
				registerListeners();

				// 注册一个默认的属性值解析器
				// 初始化所有不是懒加载的bean等操作
				finishBeanFactoryInitialization(beanFactory);
				
				// 完成容器的刷新工作,
				// 初始化LifecycleProcessor
				// 调用LifecycleProcessor的onRefresh()方法
				// 发布ContextRefreshedEvent事件
				finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

刷新容器后的一些操作,这里是空方法

设计模式中的模板方法,默认为空实现。自定义实现

	protected void afterRefresh(ConfigurableApplicationContext context,
			ApplicationArguments args) {
	}

启动容器

			listeners.started(context);

到这里容器就启动完成。spring boot的启动流程也到这里了。后面着重学习springboot是如何自动配置的,以及各个starter是如何集成的。

参考学习博文:

https://blog.csdn.net/woshilijiuyi/article/details/82350057

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值