本文基于spring-boot:1.5.14.RELEASE
本人能力有限,很多地方可能说的不够详尽,不到之处还请斧正。写本文的目的主要是巩固自己的学习,也给spring boot初学者一些帮助。
run方法会构造一个SpringApplication的实例,内部会调用initialize方法,代码如下:
private void initialize(Object[] sources) {
if (sources != null && sources.length > 0) {
this.sources.addAll(Arrays.asList(sources));
}
this.webEnvironment = deduceWebEnvironment();
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
-
把sources设置到SpringApplication的sources属性中
-
deduceWebEnvironment( )根据是否包含
"javax.servlet.Servlet","org.springframework.web.context.ConfigurableWebApplicationContext"
判断是不是web应用。 -
获取spring.factories 中所有key为ApplicationContextInitializer、ApplicationListener的值
getSpringFactoriesInstances -> SpringFactoriesLoader.loadFactoryNames(type, classLoader)) -> PropertiesLoaderUtils.loadProperties(new UrlResource(url)) -> META-INF/spring.factories
查询spring.factories可以发现如下内容
应用程序初始化器 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.context.embedded.ServerPortInfoApplicationContextInitializer
应用程序事件(ApplicationEvent)监听器 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.liquibase.LiquibaseServiceLocatorApplicationListener,\
org.springframework.boot.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.logging.LoggingApplicationListene
- 遍历stackTrace,从StackTraceElement中获取带有main方法的类,利用反射生成main类
参考:http://fangjian0423.github.io/2017/04/30/springboot-startup-analysis/
网友评论