Spring Boot

SpringBoot启动流程

首先运行SpringApplication的run方法,会执行如下这段代码

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);
			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;
	}

stopWatch 是计时用的,最终会在下面这句传入参数打印启动时长

if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}

获取监听器,开启监听;

SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();

配置环境:

ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
configureIgnoreBeanInfo(environment);

environment 就是如下这堆,指向配置信息

StandardServletEnvironment {activeProfiles=[], defaultProfiles=[default], propertySources=[ConfigurationPropertySourcesPropertySource {name='configurationProperties'}, StubPropertySource {name='servletConfigInitParams'}, StubPropertySource {name='servletContextInitParams'}, PropertiesPropertySource {name='systemProperties'}, OriginAwareSystemEnvironmentPropertySource {name='systemEnvironment'}, RandomValuePropertySource {name='random'}, OriginTrackedMapPropertySource {name='applicationConfig: [classpath:/application.yml]'}]}
@SuppressWarnings({ "unchecked", "rawtypes" })
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();
}

ClassUtils这个工具类的isPresent 方法是检查类是否存在并可以加载,如果依赖项不存在就无法加载。

this.webApplicationType 是选择什么web服务器

1.servlet 2.REACTIVE (webflux)来创建对应的上下文环境 3.none 非web项目

一般会返回SERVLET,就是普通的tomcat servlet 。实现tomcat就是要实现javax.servlet.Servlet接口

init(ServletConfig config)  初始化,只调用一次
service  该方法会在客户端请求响应中反复调用
destory  servlet容器关闭释放内存的时候调用destory方法。

webflux可以让你在web应用下也可以体验tcp长连接传输流数据, 非阻塞的web框架。可以进行响应式编程

基于反应性堆栈,而不是servlet堆栈。

如果不想打印SpringBoot这个Banner信息可以设置off,查看代码如下:

private Banner printBanner(ConfigurableEnvironment environment) {
	if (this.bannerMode == Banner.Mode.OFF) {
		return null;
	}
	ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader
			: new DefaultResourceLoader(getClassLoader());
	SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner);
	if (this.bannerMode == Mode.LOG) {
		return bannerPrinter.print(environment, this.mainApplicationClass, logger);
	}
	return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
}

可以在application.yml文件中配置:

spring: 
   main: 
      banner-mode: off

下面就是初始化通过类加载器加载META-INF/spring.factories文件中配置的,实际加载路径就是如下的:

jar:file:/C:/Users/Administrator/.m2/repository/org/springframework/boot/spring-boot/2.2.5.RELEASE/spring-boot-2.2.5.RELEASE.jar!/META-INF/spring.factories

从spring.factories文件中读取配置类和监听器,分别进行初始化,然后设置到上下文环境中。

总结下:

  • 运行程序入口main方法,调用SpringApplication.run 创建了一个SpringApplication实例
  • 设置web服务器类型webApplicationType,从META-INF/spring.factories中读取并初始化配置类和初始化监听器
  • 配置上下文环境,打印出banner信息,刷新应用程序上下文,打印启动信息