Spring boot启动源码之SpringApplication构造器


Spring启动源码之SpringApplication构造器


Spring boot项目的启动类中的main方法如下:

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

ctrl + 鼠标左键点击查看run方法:

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

这里只是包装了一层,没啥好说的,继续ctrl + 鼠标左键点击查看run方法:

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

到这里就是调用了SpringApplication的构造方法,run方法我们后续再说,先看构造方法:

/**
* Create a new {@link  SpringApplication} instance. The application context will load 
* beans from the specified primary sources (see {@link  SpringApplication class-level} 
* documentation for details. The instance can be customized before calling
* {@link  #run(String...)}. 
* @param  resourceLoader the resource loader to use 
* @param  primarySources the primary bean sources 
* @see  #run(Class, String[]) 
* @see  #setSources(Set) 
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
//设置资源加载器,但是参数为null
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
//设置主要来源primarySources变量,debug可以看到是我们的启动类
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
//获取当前classloader的启动环境 这里为 servelet 
this.webApplicationType = WebApplicationType.deduceFromClasspath();
// 按 ApplicationContextInitializer 接口,获取实例,并赋值给变量SpringApplication.initializers
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
//按 ApplicationListener 接口,获取实例,并赋值给变量SpringApplication.listeners
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//推断出当前启动的main函数所在的类
this.mainApplicationClass = deduceMainApplicationClass();
}

看起来做了非常多的事情,容我细细道来

1、WebApplicationType.deduceFromClasspath()

WebApplicationType是一个枚举类,代表的是启动的应用类型,有三种类型,NONE、SERVLET、REACTIVE。这对我们理解Spring boot还是挺关键的,其中NONE类型是不启动内嵌的webServer,标识项目并不是一个Web应用。SERVLET类型则是我们最常见的Spring MVC项目的类型,而REACTIVE则是响应式的web项目才会是这个类型,比如webflux,我对webflux的唯一印象就是在集成Spring cloud gateway时,需要将spring-web依赖替换为spring-webflux依赖,否则报错,当时弄了非常久,印象深刻。REACTIVE类型的项目是异步非阻塞的,同时可以实现如webSocket类似的功能,实现服务器与页面实时交互,不需要刷新页面就可以更新数据。相比较于SERVLET类型的项目的“命令式”交互(想要获取新数据,需要重新调接口),区别挺大的。


2、getSpringFactoriesInstances


可以看到setInitializers()和setListeners()都是调用了getSpringFactoriesInstances方法,这个方法的作用就是从spring.factories文件中加载配置,根据配置,实例化对应的实例。口说无凭,以setListeners()方法中的监听器为例:

全局查找证据

在这里插入图片描述

代码中的证据:

我们以SpringApplication的构造函数中的setListeners()方法为例

setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));

进入getSpringFactoriesInstances方法

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
   return getSpringFactoriesInstances(type, new Class<?>[] {});
}

继续深入

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
   ClassLoader classLoader = getClassLoader();
   // Use names and ensure unique to protect against duplicates
   Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
   List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
   AnnotationAwareOrderComparator.sort(instances);
   return instances;
}

关键就是这行代码:

Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));

我们进入SpringFactoriesLoader.loadFactoryNames()方法

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

很好,关键的要来了,我们看loadSpringFactories方法:

private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
   MultiValueMap<String, String> result = cache.get(classLoader);
   if (result != null) {
      return result;
   }

   try {
      Enumeration<URL> urls = (classLoader != null ?
            classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
            ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
//后续代码省略

可以看到,是从FACTORIES_RESOURCE_LOCATION中读取出来的

/**
 * The location to look for factories.
 * <p>Can be present in multiple JAR files.
 */
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

找到了, 这就是Spring通过spring.factories文件进行初始化各种initializers和listeners的证据了。


3、deduceMainApplicationClass


推断出当前启动的main函数所在的类,源码中的方法挺巧妙的,新建了一个运行时异常对象,通过这个对象获取当前的调用函数堆栈数组StackTrace,之后遍历这个堆栈数组,找到方法名为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;
}

总结

SpringApplication的构造函数了解完了,总结一下:在SpringApplication的构造函数中,初始化了一些类变量,包括primarySource、webApplicationType、initializers、listeners、mainApplicationClass用于后续使用。

我学到了什么?

1、看源码时,不要忽略构造函数,很多优秀的源码都会在你想不到的构造函数中。
2、Spring boot原来是分为三种启动类型啊,以前只知道个servlet。
3、以前也是知道spring.factories文件的,但是对于具体如何读取?那么多依赖中都有spring.factories,到底是读取哪些?我都是非常懵的,现在了解了,有了具体概念。
4、之前看Spring的refresh()源码时,对于一些系统的Listener从哪里来的没有搞清楚,这里明白了,原来是在SpringApplication构造函数中加载的。
5、可以通过新建一个运行时异常对象,获取main方法,或者一些方法名独一无二的方法所在的类。

–我是“道祖且长”,一个在互联网"苟且偷生"的Java程序员
“有任何问题,可评论,我看到就会回复”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三七有脾气

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值