首页 > 其他分享 >springboot启动流程 (1) 流程概览

springboot启动流程 (1) 流程概览

时间:2023-06-15 09:11:23浏览次数:40  
标签:springboot 流程 args 概览 Class environment context new class

本文将通过阅读源码方式分析SpringBoot应用的启动流程,不涉及Spring启动部分(有相应的文章介绍)。

本文不会对各个流程做展开分析,后续会有文章介绍详细流程。

SpringApplication类

应用启动入口

使用以下方式启动一个SpringBoot应用:

@SpringBootApplication
public class SpringBootDemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootDemoApplication.class, args);
  }
}

run方法

public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
	return run(new Class<?>[] { primarySource }, args);
}

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);
		// 获取应用env
		ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
		configureIgnoreBeanInfo(environment);
		// 打印banner
		Banner printedBanner = printBanner(environment);
		// 创建ApplicationContext
		context = createApplicationContext();
		exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
				new Class[] { ConfigurableApplicationContext.class }, context);
		// 一些准备工作
		prepareContext(context, environment, listeners, applicationArguments, printedBanner);
		// refresh ApplicationContext
		refreshContext(context);
		afterRefresh(context, applicationArguments);
		stopWatch.stop();
		if (this.logStartupInfo) {
			new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
		}
		// 调用listener
		listeners.started(context);
		// 调用ApplicationRunner和CommandLineRunner
		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;
}

获取应用env

private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
		ApplicationArguments applicationArguments) {
	// 创建StandardServletEnvironment, 会初始化四个PropertySource:
	// servletConfigInitParams, servletContextInitParams, systemProperties, systemEnvironment
	// 比如-Dserver.port=8888会在systemProperties中
	ConfigurableEnvironment environment = getOrCreateEnvironment();
	// 添加defaultProperties和命令行配置参数即CommandLinePropertySource
	// 通常都没有这两个配置
	configureEnvironment(environment, applicationArguments.getSourceArgs());
	// 使用ConfigurationPropertySourcesPropertySource封装并暴露所有的PropertySource集
	ConfigurationPropertySources.attach(environment);
	// 添加ApplicationEnvironmentPreparedEvent事件并触发multicastEvent加载应用配置文件
	listeners.environmentPrepared(environment);
	// 将spring.main.xx配置加载到SpringApplication对象
	bindToSpringApplication(environment);
	if (!this.isCustomEnvironment) {
		environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
				deduceEnvironmentClass());
	}
	ConfigurationPropertySources.attach(environment);
	return environment;
}

加载配置文件的入口在ConfigFileApplicationListener类中:

public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
	addPropertySources(environment, application.getResourceLoader());
}

protected void addPropertySources(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
	// 添加RandomValuePropertySource
	RandomValuePropertySource.addToEnvironment(environment);
	// 加载配置文件
	new Loader(environment, resourceLoader).load();
}

加载配置文件的源码较多,此处不做记录,简单梳理一下流程:

  1. 加载active profile配置文件
    • 如果配置了spring.config.additional-location或spring.config.location参数,会使用它们作为配置文件。如果这两个参数值是目录,则会从这两个目录下查找配置文件
    • 默认从classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/目录下查找application-xx.properties或application-xx.yml文件
    • 使用PropertiesPropertySourceLoader和YamlPropertySourceLoader解析配置文件
    • 会将配置参数封装成OriginTrackedMapPropertySource类型对象,使用applicationConfig: [classpath:/application-dev.yml]之类的字符串作为PropertySource的名称
  2. 加载默认的application.properties或application.yml文件
  3. 解析出来的所有PropertySource都会添加到environment的propertySources中,propertySources是一个MutablePropertySources对象,管理着所有的PropertySource集,在这个过程中,添加的先后顺序决定了配置的优先级

创建ApplicationContext

protected ConfigurableApplicationContext createApplicationContext() {
	Class<?> contextClass = this.applicationContextClass;
	if (contextClass == null) {
		try {
			switch (this.webApplicationType) {
			case SERVLET:
				// AnnotationConfigServletWebServerApplicationContext类
				contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
				break;
			case REACTIVE:
				// AnnotationConfigReactiveWebServerApplicationContext类
				contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
				break;
			default:
				// AnnotationConfigApplicationContext类
				contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
			}
		} catch (ClassNotFoundException ex) {
			throw new IllegalStateException("Unable create a default ApplicationContext", ex);
		}
	}
	return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}

prepareContext

private void prepareContext(
		ConfigurableApplicationContext context, ConfigurableEnvironment environment,
		SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments,
		Banner printedBanner) {
	context.setEnvironment(environment);
	postProcessApplicationContext(context);
	// Apply any ApplicationContextInitializers to the context before it is refreshed.
	// ApplicationContextInitializers集是在创建SpringApplication对象的时候初始化的
	applyInitializers(context);
	// 触发contextPrepared事件
	listeners.contextPrepared(context);
	if (this.logStartupInfo) {
		logStartupInfo(context.getParent() == null);
		logStartupProfileInfo(context);
	}
	// 获取BeanFactory并注册必要的Bean
	ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
	// 注册启动参数
	beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
	// 注册banner printer
	if (printedBanner != null) {
		beanFactory.registerSingleton("springBootBanner", printedBanner);
	}
	// 设置是否允许Bean覆盖,使用spring.main.allowBeanDefinitionOverriding参数配置
	if (beanFactory instanceof DefaultListableBeanFactory) {
		((DefaultListableBeanFactory) beanFactory)
				.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
	}
	if (this.lazyInitialization) {
		context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
	}
	// Load the sources
	Set<Object> sources = getAllSources();
	// 将SpringApplication.run(Xxx.class, args)方法传入的Class注册到容器
	// 使用AnnotatedBeanDefinitionReader.register(Class<?>...)方法注册启动类
	load(context, sources.toArray(new Object[0]));
	// 触发contextLoaded事件
	listeners.contextLoaded(context);
}

refreshApplicationContext

protected void refresh(ConfigurableApplicationContext applicationContext) {
	applicationContext.refresh();
}

调用的是ServletWebServerApplicationContext的refresh方法:

public final void refresh() throws BeansException, IllegalStateException {
	try {
		super.refresh();
	} catch (RuntimeException ex) {
		// 关闭web server
		WebServer webServer = this.webServer;
		if (webServer != null) {
			webServer.stop();
		}
		throw ex;
	}
}

绝大多数的refresh逻辑都在AbstractApplicationContext类里面,ServletWebServerApplicationContext中会在onRefresh阶段创建webServer:

protected void onRefresh() {
	super.onRefresh();
	try {
		createWebServer();
	} catch (Throwable ex) {
		throw new ApplicationContextException("Unable to start web server", ex);
	}
}

调用ApplicationRunner和CommandLineRunner

private void callRunners(ApplicationContext context, ApplicationArguments args) {
	List<Object> runners = new ArrayList<>();
	runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
	runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
	AnnotationAwareOrderComparator.sort(runners);
	for (Object runner : new LinkedHashSet<>(runners)) {
		if (runner instanceof ApplicationRunner) {
			callRunner((ApplicationRunner) runner, args);
		}
		if (runner instanceof CommandLineRunner) {
			callRunner((CommandLineRunner) runner, args);
		}
	}
}

SpringBootApplication注解

指示一个配置类,该类声明一个或多个@Bean方法,并触发自动配置和组件扫描。这是一个方便的注解,相当于声明@Configuration、@EnableAutoConfiguration和@ComponentScan注解。

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 */
	@AliasFor(annotation = EnableAutoConfiguration.class)
	Class<?>[] exclude() default {};

	/**
	 * Exclude specific auto-configuration class names such that they will never be
	 * applied.
	 */
	@AliasFor(annotation = EnableAutoConfiguration.class)
	String[] excludeName() default {};

	/**
	 * Base packages to scan for annotated components. Use scanBasePackageClasses
	 * for a type-safe alternative to String-based package names.
	 */
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
	String[] scanBasePackages() default {};

	/**
	 * Type-safe alternative to scanBasePackages for specifying the packages to
	 * scan for annotated components. The package of each class specified will be scanned.
	 */
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
	Class<?>[] scanBasePackageClasses() default {};

	/**
	 * The BeanNameGenerator class to be used for naming detected components
	 * within the Spring container.
	 */
	@AliasFor(annotation = ComponentScan.class, attribute = "nameGenerator")
	Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;

	/**
	 * Specify whether @Bean methods should get proxied in order to enforce
	 * bean lifecycle behavior, e.g. to return shared singleton bean instances even in
	 * case of direct @Bean method calls in user code. This feature requires
	 * method interception, implemented through a runtime-generated CGLIB subclass which
	 * comes with limitations such as the configuration class and its methods not being
	 * allowed to declare final.
	 */
	@AliasFor(annotation = Configuration.class)
	boolean proxyBeanMethods() default true;
}

SpringBootConfiguration注解

指示一个类提供Spring Boot application @Configuration功能。可以替代Spring的标准@Configuration注解,以便可以自动找到配置类。

应用程序应该只标注一个@SpringBootConfiguration,大多数SpringBoot应用程序将从@SpringBootApplication继承它。

@Configuration
public @interface SpringBootConfiguration {

	@AliasFor(annotation = Configuration.class)
	boolean proxyBeanMethods() default true;
}

EnableAutoConfiguration注解

启用SpringBoot自动装配功能,尝试猜测和配置可能需要的组件Bean。

自动装配类通常是根据类路径和定义的Bean来应用的。例如,如果类路径上有tomcat-embedded.jar,那么可能需要一个TomcatServletWebServerFactory(除非已经定义了自己的Servlet WebServerFactory Bean)。

自动装配试图尽可能地智能化,并将随着开发者定义自己的配置而取消自动装配相冲突的配置。开发者可以使用exclude()排除不想使用的配置,也可以通过spring.autoconfig.exclude属性排除这些配置。自动装配总是在用户定义的Bean注册之后应用。

用@EnableAutoConfiguration注解标注的类所在包具有特定的意义,通常用作默认扫描的包。通常建议将@EnableAutoConfiguration(如果没有使用@SpringBootApplication注解)放在根包中,以便可以搜索所有子包和类。

自动装配类是普通的Spring @Configuration类,使用SpringFactoriesLoader机制定位。通常使用@Conditional方式装配,最常用的是@ConditionalOnClass和@ConditionalOnMissingBean注解。

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 */
	Class<?>[] exclude() default {};

	/**
	 * Exclude specific auto-configuration class names such that they will never be
	 * applied.
	 * 当类路径下没有指定的类时,可以使用这个属性指定排除的类
	 */
	String[] excludeName() default {};
}

AutoConfigurationPackage注解

Registers packages with AutoConfigurationPackages. When no base packages or base package classes are specified, the package of the annotated class is registered.

@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {

	String[] basePackages() default {};

	Class<?>[] basePackageClasses() default {};
}

AutoConfigurationImportSelector类

DeferredImportSelector接口的实现类,处理自动装配,导出所有需要自动装配的类。

创建WebServer

SpringBoot会在onRefresh阶段创建webServer,首先从spring容器获取ServletWebServerFactory,然后调用getWebServer方法创建webServer。

getWebServer方法需要传入ServletContextInitializer集来初始化ServletContext。

@FunctionalInterface
public interface ServletContextInitializer {

	void onStartup(ServletContext servletContext) throws ServletException;
}

我们开发者如果需要使用ServletContextInitializer来初始化ServletContext的话,也可以编写一个实现类,然后将其注册到spring容器即可。

另外,SpringBoot还会自动装配DispatcherServletAutoConfiguration类,这个类会创建DispatcherServlet和DispatcherServletRegistrationBean。DispatcherServlet是SpringWebMvc的最核心组件,DispatcherServletRegistrationBean实现了ServletContextInitializer接口,可以将DispatcherServlet注册到ServletContext。以TomcatServletWebServerFactory为例,这个类会通过TomcatStarter来调用所有的ServletContextInitializer,TomcatStarter实现了ServletContainerInitializer接口,Tomcat的ServletContext在启动阶段会调用ServletContainerInitializer的onStartup方法来初始化Servlet容器。

SpringBoot启动流程

  • 初始化environment应用配置参数:servletConfigInitParams, servletContextInitParams, systemProperties, systemEnvironment及配置文件等
  • 创建ApplicationContext对象,SpringBoot应用默认使用的是AnnotationConfigServletWebServerApplicationContext类
  • prepareContext阶段:触发一些事件,将启动类注册到Spring容器
  • refresh阶段:扫描应用组件,自动装配
  • onRefresh阶段:创建并初始化WebServer
  • 调用ApplicationRunner和CommandLineRunner

标签:springboot,流程,args,概览,Class,environment,context,new,class
From: https://www.cnblogs.com/xugf/p/17481884.html

相关文章

  • SpringBoot集成支付宝 - 少走弯路就看这篇
    最近在做一个网站,后端采用了SpringBoot,需要集成支付宝进行线上支付,在这个过程中研究了大量支付宝的集成资料,也走了一些弯路,现在总结出来,相信你读完也能轻松集成支付宝支付。在开始集成支付宝支付之前,我们需要准备一个支付宝商家账户,如果是个人开发者,可以通过注册公司或者让有公......
  • MONAI Label 安装流程及使用攻略
    这部分为monailabel的安装实操,分为服务端安装和客户端安装。预祝大家顺利安装。如果遇到问题,可以在交流群里探讨。在开始前,可以把以下链接打开,官方安装教程monailabelgithub服务器(Server)端安装服务器电脑条件:可以是Ubuntu和Windows操作系统,但必须要有GPU/CUDA。并能支持深......
  • springboot+elementUI
    功能简介后端用springboot实现数据库的增删改查,前端用vue中的elementUI编写,实现简单的数据展示和增删改。环境准备1.vue环境vue安装:https://www.cnblogs.com/xiaozhaoboke/p/16888421.html安装好后打开vueui进入项目管理器,创建项目添加elementUI插件和axios插件2......
  • 深浅拷贝、第三方模块的下载与安装、开发流程
    深浅拷贝详解1.对于不可变对象,深拷贝和浅拷贝的效果是一样的,因为不可变对象不需要在内存中复制2.对于可变对象,深拷贝和浅拷贝的效果是有区别的,主要原因在于可变对象自身的可变性质浅拷贝1.1使用数据类型本身的构造器list1=[1,2,3]list2=list(list1)print(list2)pri......
  • springboot-feign接口压缩异常
    WARNorg.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver-Resolved[org.springframework.http.converter.HttpMessageNotReadableException:JSONparseerror:Illegalcharacter((CTRL-CHAR,code31)):onlyregularwhitespace(\r,\......
  • 01企业项目开发流程,你平时的工作流程,pip永久换源,虚拟环境和虚拟环境搭建,luffy后台创建
    1企业项目类型#1面向互联网用户:商城类项目 -微信小程序商城-app商城-得物-饿了么-问卷网#2面向互联网用户:二手交易类的 -咸鱼 -转转#3公司内部项目:python写的重点#传统软件行业,互联网 -给客户做软件:国家电网,社保局,银行,医院,大客户......
  • 【Netty】Netty部分源码分析(启动流程,EventLoop,accept流程,read流程)
    源码分析Netty源码中调用链特别长,且涉及到线程切换等步骤,令人头大:)1启动剖析我们就来看看netty中对下面的代码是怎样进行处理的//1netty中使用NioEventLoopGroup(简称nioboss线程)来封装线程和selectorSelectorselector=Selector.open();//2创建NioServerSo......
  • SpringBoot使用自定义的logback日志
    1.介绍描述:主要由三个模块构成logback-core:核心代码块(不介绍)logback-classic:实现了slf4j的api,加入该依赖可以实现log4j的api。logback-access:访问模块与servlet容器集成提供通过http来访问日志的功能(也就是说不需要访问服务器,直接在网页上就可以访问日志文件,实现HTTP访问......
  • SpringBoot使用自定义日志注解,配置切面
    1.使用技巧以下是需要注意的部分:在环绕通知中使用ProceedingJoinPoint,控制目标方法的运行。在其他通知类型中使用JoinPoint。如果使用JoinPoint则必须位于参数的第一位。ProceedingJoinPoint中有特殊的方法proceed()。当有多个切面时,使用@Order(11)来指定注解的优先级。......
  • 根据不同场景(是否需要连接数据库)启动SpringBoot
    1.场景描述描述:使用场景:项目中的一部分业务不需要进行数据库操作,当只使用这部分功能时,希望程序启动时可以不进行数据库的连接项目中需要数据库相关的业务时再进行配置注意:Springboot在启动时会根据pom.xml启动器来判断是否开启相应的自动配置解决方式:设置一个包......