springboot启动流程分析

分析springboot启动流程

准备

最简单的springboot项目代码,如下:

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

代码分析

按照代码执行顺序记录流程。

1、SpringApplication类

在启动类EurekaApplication中执行的是SpringApplication类的静态方法run。第一个参数是启动类的class对象,第二个参数是启动main方法的参数。

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

1.1、创建SpringApplication对象

创建SpringApplication对象的主逻辑如下。其中resourceLoader为null,primarySources是EurekaApplication的class对象。

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 = deduceWebApplicationType();
	setInitializers((Collection) getSpringFactoriesInstances(
			ApplicationContextInitializer.class));
	setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
	this.mainApplicationClass = deduceMainApplicationClass();
}
1.1.1、设置SpringApplication对象的属性
  • resourceLoader 为null。

  • primarySources 集合只有启动类一个元素。

  • webApplicationType :应用的启动类型,三种,具体参考WebApplicationType类。一般是SERVLET(The application should run as a servlet-based web application and should start an embedded servlet web server.)

  • setInitializers:初始化springboot应用启动过程中后续要用到的容器启动类(key=ApplicationContextInitializer,细节参考后面的详细介绍)。初始化完毕后,设置为SpringApplication的属性initializers。启动类如下图:
    在这里插入图片描述

  • setListeners:初始化监听器。初始化完毕后,设置为SpringApplication的属性listeners(key=ApplicationListener,细节参考后面的详细介绍)。监听器如下图:
    在这里插入图片描述

  • 初始化initializer和listener的细节
    org.springframework.core.io.support.SpringFactoriesLoader中的loadFactoryNames方法和loadSpringFactories方法。
    首先是loadFactoryNames方法,获取FactoryBean的name。代码如下:

public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
	String factoryClassName = factoryClass.getName();
	return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}

private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
	MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
	if (result != null) {
		return result;
	} else {
		try {
			Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
			LinkedMultiValueMap result = new LinkedMultiValueMap();

			while(urls.hasMoreElements()) {
				URL url = (URL)urls.nextElement();
				UrlResource resource = new UrlResource(url);
				Properties properties = PropertiesLoaderUtils.loadProperties(resource);
				Iterator var6 = properties.entrySet().iterator();

				while(var6.hasNext()) {
					Entry<?, ?> entry = (Entry)var6.next();
					List<String> factoryClassNames = Arrays.asList(StringUtils.commaDelimitedListToStringArray((String)entry.getValue()));
					result.addAll((String)entry.getKey(), factoryClassNames);
				}
			}

			cache.put(classLoader, result);
			return result;
		} catch (IOException var9) {
			throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var9);
		}
	}
}

首先加载META-INF/spring.factories文件。下载springboot源码,可知文件位置如下所示:
在这里插入图片描述
文件内容如下(不同版本之间有小的差异):

# PropertySource Loaders
org.springframework.boot.env.PropertySourceLoader=\
org.springframework.boot.env.PropertiesPropertySourceLoader,\
org.springframework.boot.env.YamlPropertySourceLoader

# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
org.springframework.boot.context.event.EventPublishingRunListener

# Error Reporters
org.springframework.boot.SpringBootExceptionReporter=\
org.springframework.boot.diagnostics.FailureAnalyzers

# Application Context Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

# Environment Post Processors
org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\
org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor,\
org.springframework.boot.env.SystemEnvironmentPropertySourceEnvironmentPostProcessor

# Failure Analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.diagnostics.analyzer.BeanCurrentlyInCreationFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BeanDefinitionOverrideFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BeanNotOfRequiredTypeFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BindFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BindValidationFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.UnboundConfigurationPropertyFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.ConnectorStartFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.NoSuchMethodFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.NoUniqueBeanDefinitionFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.PortInUseFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.ValidationExceptionFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.InvalidConfigurationPropertyNameFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.InvalidConfigurationPropertyValueFailureAnalyzer

# FailureAnalysisReporters
org.springframework.boot.diagnostics.FailureAnalysisReporter=\
org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter
  • 确定mainApplicationClass,即为main方法被执行的EurekaApplication类。判断当前线程的栈帧中,类的方法名是main的类。
    在这里插入图片描述

至此,SpringApplication类创建完毕。

1.2、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;
}
1.2.1、创建StopWatch对象并执行start方法
  • StopWatch:Simple stop watch, allowing for timing of a number of tasks, exposing(暴露; 揭露; 显露; 曝光) total running time and running time for each named task.
    默认的名字是空字符串。
    start方法是简单的属性赋值。
1.2.2、定义上下文对象和启动异常记录集合

ConfigurableApplicationContext context = null;
Collection exceptionReporters = new ArrayList<>();

1.2.3、设置系统属性

configureHeadlessProperty();

1.2.4、创建事件传播监听器并启动

SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting(); // 不知道具体干了什么

1.2.5、创建启动参数对象

ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
这里没有传入参数,即args是空字符串数组。

1.2.6、创建启动参数对象及上下文环境预处理

对上下文环境预处理
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
为打印springboot的banner做准备
Banner printedBanner = this.printBanner(environment);

1.2.7、创建容器对象

context = this.createApplicationContext();
具体逻辑如下。根据启动类型判断应该加载什么class,然后反射创建对象。

protected ConfigurableApplicationContext createApplicationContext() {
	Class<?> contextClass = this.applicationContextClass;
	if (contextClass == null) {
		try {
			switch(this.webApplicationType) {
			case SERVLET:
				contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");
				break;
			case REACTIVE:
				contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");
				break;
			default:
				contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
			}
		} catch (ClassNotFoundException var3) {
			throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
		}
	}

	return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
}
1.2.8、创建记录容器启动记录对象

exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
具体有哪些,参考META-INF/spring.factories文件,key=org.springframework.boot.diagnostics.FailureAnalyzer。

1.2.9、容器对象初始化

this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);

猜你喜欢

转载自blog.csdn.net/yulong1026/article/details/82894065