美文网首页Spring BootSpringBoot精选
spring boot 源码- initalize方法

spring boot 源码- initalize方法

作者: Shine_Chan | 来源:发表于2018-07-27 13:17 被阅读5次

本文基于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();

}

  1. 把sources设置到SpringApplication的sources属性中

  2. deduceWebEnvironment( )根据是否包含 "javax.servlet.Servlet","org.springframework.web.context.ConfigurableWebApplicationContext"判断是不是web应用。

  3. 获取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

  1. 遍历stackTrace,从StackTraceElement中获取带有main方法的类,利用反射生成main类

参考:http://fangjian0423.github.io/2017/04/30/springboot-startup-analysis/

相关文章

网友评论

    本文标题:spring boot 源码- initalize方法

    本文链接:https://www.haomeiwen.com/subject/rsnwmftx.html