SpringBoot启动

基于spingboot 2.1.1

run方法

   public static ConfigurableApplicationContext run(Class<?> primarySource,
   		String... args) {
   	return run(new Class<?>[] { primarySource }, args);
   }
// 最终调用SpringApplication实例的run方法。
   public static ConfigurableApplicationContext run(Class<?>[] primarySources,
   		String[] args) {
   	return new SpringApplication(primarySources).run(args);
   }
public ConfigurableApplicationContext run(String... args) {
   	StopWatch stopWatch = new StopWatch();
   	stopWatch.start();
   	ConfigurableApplicationContext context = null;
   	Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
   	configureHeadlessProperty();
   	SpringApplicationRunListeners listeners = getRunListeners(args);
   	listeners.starting();
   	try {
//前置配置信息获取,环境信息准备
   		ApplicationArguments applicationArguments = new DefaultApplicationArguments(
   				args);
   		ConfigurableEnvironment environment = prepareEnvironment(listeners,
   				applicationArguments);
   		configureIgnoreBeanInfo(environment);
   		Banner printedBanner = printBanner(environment);
//根据SpringApplication对象中的webApplication类型创建对应的context实例
   		context = createApplicationContext();
   		exceptionReporters = getSpringFactoriesInstances(
   				SpringBootExceptionReporter.class,
   				new Class[] { ConfigurableApplicationContext.class }, context);
//核心三个处理方法
   		prepareContext(context, environment, listeners, applicationArguments,
   				printedBanner);
   		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;
   }

SpringApplication

//SpringApplication构造函数主要是配置一些基础信息,然后从工厂实例获取一些成员(约定大于配置的体现)
	public SpringApplication(Class<?>... primarySources) {
		this(null, primarySources);
	}
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
		this.resourceLoader = resourceLoader;
		Assert.notNull(primarySources, "PrimarySources must not be null");
		this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
		this.webApplicationType = WebApplicationType.deduceFromClasspath();
		setInitializers((Collection) getSpringFactoriesInstances(
				ApplicationContextInitializer.class));
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
		this.mainApplicationClass = deduceMainApplicationClass();
	}

prepareContext

private void prepareContext(ConfigurableApplicationContext context,
			ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
			ApplicationArguments applicationArguments, Banner printedBanner) {
		context.setEnvironment(environment);
//此方法实际只会为应用程序上下文的bean工厂设置ConversionService(其他两个if条件会因false跳过)。ConversionService表示类型转换服务,如将字符串转换为Long,字符串转换为日期等。在处理属性和创建Bean对象等很多场景都会使用到。
		postProcessApplicationContext(context);
//(重要)加载所有的初始化器,用于初始化ConfigurableApplicationContext
		applyInitializers(context);
		listeners.contextPrepared(context);
//新版本这里有个额外操作bootstrapContext.close
		if (this.logStartupInfo) {
			logStartupInfo(context.getParent() == null);
			logStartupProfileInfo(context);
		}
//其他准备工作
		// Add boot specific singleton beans
		ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
		beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
		if (printedBanner != null) {
			beanFactory.registerSingleton("springBootBanner", printedBanner);
		}
		if (beanFactory instanceof DefaultListableBeanFactory) {
			((DefaultListableBeanFactory) beanFactory)
					.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
		}
		// Load the sources
		Set<Object> sources = getAllSources();
		Assert.notEmpty(sources, "Sources must not be empty");
		load(context, sources.toArray(new Object[0]));
		listeners.contextLoaded(context);
	}

refreshContext

//刷新上下文并注册一个shutdown hook
private void refreshContext(ConfigurableApplicationContext context) {
//ServletWebServerApplicationContext在AbstractApplicationContext的refresh方法外添加一层try catch,处理refresh异常下需要执行的命令
		refresh(context);
		if (this.registerShutdownHook) {
			try {
				context.registerShutdownHook();
			}
			catch (AccessControlException ex) {
				// Not allowed in some environments.
			}
		}
	}

简要总结

SpringBoot的run流程里主要是在Spring本身的refresh操作前对环境和部分context成员基于约定和配置进行了初始化(尤其是初始化器的加载),并在多个环节对Context的处理情况进行广播(监听器在前面流程中基于spi实现并在context中设置)。最终使用运行器基于两种参数来源(app和命令行)执行一些业务初始化操作。

参考

https://www.cnblogs.com/hld123/p/18399925
https://blog.csdn.net/lodog1/article/details/105309873

posted @   hwh405  阅读(5)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示