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程序员
“有任何问题,可评论,我看到就会回复”
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~