SpringBoot启动流程

概要

通常使用spring的模板创建的springboot启动类的main方法中只有一句话 SpringApplication.run(App.class, args);。将其拆开后大致分为两个过程,new SpringApplication application = new SpringApplication(App.class);application.run(args);下面分别说明new SpringApplication(App.class)application.run(args);两个部分。

1. 创建SpringApplication的过程(new SpringApplication(App.class))

整个过程分为如下几部分:

  1. 根据类路径推断web应用类型
  2. 加载BootstrapRegistryInitializer
  3. 加载ApplicationContextInitializer
  4. 加载ApplicationListener
  5. 根据栈帧信息推断主类
	public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
   
		this.resourceLoader = resourceLoader;
		Assert.notNull(primarySources, "PrimarySources must not be null");
		this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
		// 1. 根据类路径推断web应用类型
		this.webApplicationType = WebApplicationType.deduceFromClasspath();
		// 2. 加载BootstrapRegistryInitializer
		this.bootstrapRegistryInitializers = new ArrayList<>(
				getSpringFactoriesInstances(BootstrapRegistryInitializer.class));
		// 3. 加载ApplicationContextInitializer
		setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
		
		// 4. 加载ApplicationListener
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
		// 5. 根据栈帧信息推断主类
		this.mainApplicationClass = deduceMainApplicationClass();
	}

1.1. 根据类路径推断web应用类型

this.webApplicationType = WebApplicationType.deduceFromClasspath();
WebApplicationType中的静态方法deduceFromClasspath根据特定是否存在类名判断应用程序类型:

// servlet应用指示类
private static final String[] SERVLET_INDICATOR_CLASSES = {
    "jakarta.servlet.Servlet",
		"org.springframework.web.context.ConfigurableWebApplicationContext" };
// webmve指示类
private static final String WEBMVC_INDICATOR_CLASS = "org.springframework.web.servlet.DispatcherServlet";
// webflux指示类
private static final String WEBFLUX_INDICATOR_CLASS = "org.springframework.web.reactive.DispatcherHandler";
// jersey指示类
private static final String JERSEY_INDICATOR_CLASS = "org.glassfish.jersey.servlet.ServletContainer";
static WebApplicationType deduceFromClasspath() {
   
	// 若类路径包含WEBMVC_INDICATOR_CLASS,
	// 且WEBMVC_INDICATOR_CLASS及JERSEY_INDICATOR_CLASS均不存在,
	// 则此应用为REACTIVE类型应用
	if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
			&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
   
		return WebApplicationType.REACTIVE;
	}
	// 若SERVLET_INDICATOR_CLASSES中的某个类不存在
	// 则此应用不是web应用
	for (String className : SERVLET_INDICATOR_CLASSES) {
   
		if (!ClassUtils
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JebWoo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值