springboot 源码理解

java1234

共 6849字,需浏览 14分钟

 · 2020-12-24

点击上方蓝色字体,选择“标星公众号”

优质文章,第一时间送达

66套java从入门到精通实战课程分享

最近在看springboot 启动流程,以下就是我自己对springboot启动时执行流程的一些理解。我使用的springboot版本为 2.2.11.

开始源码阅读

package com.example.demo;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class DemoApplication {
 
 public static void main(String[] args) {
 
  SpringApplication.run(DemoApplication.class,args);
 }
}

    /**
  * Static helper that can be used to run a {@link SpringApplication} from the
  * specified sources using default settings and user supplied arguments.
  * @param primarySources the primary sources to load
  * @param args the application arguments (usually passed from a Java main method)
  * @return the running {@link ApplicationContext}
  */
 public static ConfigurableApplicationContext run(Class[] primarySources, String[] args) {
  return new SpringApplication(primarySources).run(args);
 }

由此可以看出springboot 在启动的过程主要是通过两个部分来进行完成的。1,构造器初始化 2.run方法执行的逻辑。     

首先看下构造器里面实现的逻辑,我先上一张图,主要的执行如下图所示。

 

public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
  
        // 默认为null
        this.resourceLoader = resourceLoader;
  Assert.notNull(primarySources, "PrimarySources must not be null");
        // 1. 初始化主的资源
  this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
        // 2. 推断应用类型 
  this.webApplicationType = WebApplicationType.deduceFromClasspath();
        // 3. 初始化所有实现 ApplicationContextInitializer的子类
  setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
        // 4. 初始化所有的实现ApplicationListener 的监听器,过程和3中的逻辑是一样的
  setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
        // 5. 获取mian方法  (这块的思路比较好,以下会有介绍)
  this.mainApplicationClass = deduceMainApplicationClass();
 }

 2.推断应用类型,这个就是根据类是否加载来判断应用的类型,我引用的包为spring-boot-starter-web 因此为SERVLET类型,感兴趣的可以看下这块源码。

 3. 初始化所有实现ApplicationContextInitializer类型应用上下文

private  Collection getSpringFactoriesInstances(Class type) {
  return getSpringFactoriesInstances(type, new Class[] {});
 }
 
private  Collection getSpringFactoriesInstances(Class type, Class[] parameterTypes, Object... args) {
        // 获取类加载器
  ClassLoader classLoader = getClassLoader();
  // Use names and ensure unique to protect against duplicates
        // 获取工程名称
  Set names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
        // 创建bena工厂实例
  List instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
        // 排序
  AnnotationAwareOrderComparator.sort(instances);
  return instances;
 }

其中SpringFactoriesLoader.loadFactoryNames(type, classLoader) 这个方式是重点,意思就是在classpath 路径下获取接口的实现类名称,获取之后将其放入到缓存中,方便后续的处理

public static List loadFactoryNames(Class factoryType, @Nullable ClassLoader classLoader) {
  String factoryTypeName = factoryType.getName();
  return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
 }
 
 private static Map> loadSpringFactories(@Nullable ClassLoader classLoader) {
  MultiValueMap result = cache.get(classLoader);
  if (result != null) {
   return result;
  }
 
  try {
        // FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
        // 获取加载路径
   Enumeration urls = (classLoader != null ?
     classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
     ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
   result = new LinkedMultiValueMap<>();
   while (urls.hasMoreElements()) {
    URL url = urls.nextElement();
    UrlResource resource = new UrlResource(url);
    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
    for (Map.Entry entry : properties.entrySet()) {
     String factoryTypeName = ((String) entry.getKey()).trim();
     for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
      result.add(factoryTypeName, factoryImplementationName.trim());
     }
    }
   }
   cache.put(classLoader, result);
   return result;
  }
  catch (IOException ex) {
   throw new IllegalArgumentException("Unable to load factories from location [" +
     FACTORIES_RESOURCE_LOCATION + "]", ex);
  }
 }

4. 中获取监听器的方法和3中的是相同的套路。

5. 中获取main方法的思路比较好,是直接new出一个运行期的异常通过堆栈信息来获取main方法,这个思路比较好。

private Class deduceMainApplicationClass() {
  try {
   StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
   for (StackTraceElement stackTraceElement : stackTrace) {
    if ("main".equals(stackTraceElement.getMethodName())) {
     return Class.forName(stackTraceElement.getClassName());
    }
   }
  }
  catch (ClassNotFoundException ex) {
   // Swallow and continue
  }
  return null;
 }

到此springboot实例化中做的初始化工作已经完成了,接下来就是run方法中的逻辑了。

public ConfigurableApplicationContext run(String... args) {
        // 计时器,相当于System.currentTimeMillis()获取时间进行相减来获取方法的耗时时间
  StopWatch stopWatch = new StopWatch();
  stopWatch.start();
  ConfigurableApplicationContext context = null;
  Collection exceptionReporters = new ArrayList<>();
        // 设置环境及没有鼠标,键盘这样的硬件信息
  configureHeadlessProperty();
        // 获取监听器
  SpringApplicationRunListeners listeners = getRunListeners(args);
        // 监听器开启,进行广播时间
  listeners.starting();
  try {
            // 获取默认的应用参数
   ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            // 加载系统配置及用户自定义配置
   ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
            // 设置忽略的bean信息
   configureIgnoreBeanInfo(environment);
            // 打印banner,
   Banner printedBanner = printBanner(environment);
            // 创建IOC容器
   context = createApplicationContext();
            // 加载异常的类型信息,和构造方法中的是相同的套路
   exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
     new Class[] { ConfigurableApplicationContext.class }, context);
            // IOC容器前置处理
   prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            // 刷新容器
   refreshContext(context);
            // IOC容器后置处理
   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;
 }

总结了下run方法的主要执行流程



版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:

https://blog.csdn.net/dangyongkang/article/details/111031858





粉丝福利:Java从入门到入土学习路线图

???

?长按上方微信二维码 2 秒


感谢点赞支持下哈 

浏览 2
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报