本系列文章基于SpringBoot 版本2.1.4
有些文章分析SpringBoot源码是从@SpringBootApplication这个注解开始,实际上这个注解开始发挥作用,包括内部的@Import被解析,都是在Spring容器初始化的流程中进行的,而在这之前,在还没有Spring容器的时候,SpringBoot已经做了很多初始化工作,其中也有很多扩展点可以让我们加以利用,本系列文章将从SpringBoot的启动类开始,结合项目的初始化进程,循序渐进地对SpringBoot源码做一个剖析
通常来说,一个基本的SpringBoot应用启动类长这个样子,调用SpringApplication的静态方法run,传入当前类的class以及启动参数args
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
进入run方法,把第一个class参数转化为数组类型,调用同名方法
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class[]{primarySource}, args);
}
继续跟进,调用SpringApplication的构造方法,new出SpringApplication实例后调用它的run方法,传入启动参数
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return (new SpringApplication(primarySources)).run(args);
}
先看一下SpringApplication对象的初始化过程
public SpringApplication(Class... primarySources) {
this((ResourceLoader)null, primarySources);
}
public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
this.sources = new LinkedHashSet();
this.bannerMode = Mode.CONSOLE;
this.logStartupInfo = true;
this.addCommandLineProperties = true;
this.addConversionService = true;
this.headless = true;
this.registerShutdownHook = true;
this.additionalProfiles = new HashSet();
this.isCustomEnvironment = false;
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
this.webApplicationType = WebApplicationType.deduceFromClasspath();
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = this.deduceMainApplicationClass();
}
前面都是设置一些默认参数,重点分析后面四行代码
推断应用类型
第一行是推断应用类型,这个涉及到后面的环境变量维护
共有三种类型,NONE、SERLET、REACTIVE
NONE就是不提供web服务,SERVLET是一个普通的web应用,现在大多数SpringBoot应用都属于这种,REACTIVE主要用于spring5.0新推出的WebFlux,异步非阻塞的响应式架构
public enum WebApplicationType {
NONE,
SERVLET,
REACTIVE;
...
}
推断方法
static WebApplicationType deduceFromClasspath() {
if (ClassUtils.isPresent("org.springframework.web.reactive.DispatcherHandler", (ClassLoader)null) && !ClassUtils.isPresent("org.springframework.web.servlet.DispatcherServlet", (ClassLoader)null) && !ClassUtils.isPresent("org.glassfish.jersey.servlet.ServletContainer", (ClassLoader)null)) {
return REACTIVE;
} else {
String[] var0 = SERVLET_INDICATOR_CLASSES;
int var1 = var0.length;
for(int var2 = 0; var2 < var1; ++var2) {
String className = var0[var2];
if (!ClassUtils.isPresent(className, (ClassLoader)null)) {
return NONE;
}
}
return SERVLET;
}
}
private static final String[] SERVLET_INDICATOR_CLASSES = new String[]{"javax.servlet.Servlet", "org.springframework.web.context.ConfigurableWebApplicationContext"};
逻辑也比较简单
- 如果classpath下有DispatcherHandler(引入了WebFlux),并且没有DispatcherServlet(引入SpringMVC)和ServletContainer(引入jersey),就返回REACTIVE
- 如果同时存在javax.servlet.Servlet和ConfigurableWebApplicationContext,就是SERVLET
- 否则就是NONE
一般来说我们的应用就是普通的SpringBoot应用,使用SpringMVC,返回类型就是SERVLET,对于REACTIVE类型的应用,会启动内置的netty作为服务器
后续会根据这里推断出的webApplicationType决定初始化哪种Environment存储环境变量
setInitializers
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
这里有个比较重要的方法:getSpringFactoriesInstances
这个方法的作用是到classpath下的META-INF/spring.factories文件中找到指定类型的实现
看一下它的大概逻辑
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
return this.getSpringFactoriesInstances(type, new Class[0]);
}
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = this.getClassLoader();
Set<String> names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = this.createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
进入loadFactoryNames方法
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}
继续跟进loadSpringFactories
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
if (result != null) {
return result;
} else {
try {
Enumeration<URL> urls = classLoader != null ?
classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
LinkedMultiValueMap result = new LinkedMultiValueMap();
while(urls.hasMoreElements()) {
URL url = (URL)urls.nextElement();
UrlResource resource = new UrlResource(url);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
Iterator var6 = properties.entrySet().iterator();
while(var6.hasNext()) {
Entry<?, ?> entry = (Entry)var6.next();
String factoryClassName = ((String)entry.getKey()).trim();
String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
int var10 = var9.length;
for(int var11 = 0; var11 < var10; ++var11) {
String factoryName = var9[var11];
result.add(factoryClassName, factoryName.trim());
}
}
}
cache.put(classLoader, result);
return result;
} catch (IOException var13) {
throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);
}
}
}
先从缓存里获取,如果缓存没有的话,就加载classpath下所有的META-INF/spring.factories文件,解析其中的内容,存储到一个Map<String, List< String>>中,key是spring.factories中的前缀,value是对应值根据逗号分割的列表
解析完文件后,根据key找指定的实现类,这里传入的类型是ApplicationContextInitializer
通过debug,发现一共找到了6个实现类
看名字,大概是在spring-boot和spring-boot-autoconfigure包下,去对应的META-INF/spring.factories找一下
spring-boot下有4个
spring-boot-autoconfigure下有2个
找到这些类后,通过反射实例化,获取实例列表,使用的是无参构造函数
然后存储在SpringApplication的initializers变量中
public void setInitializers(Collection<? extends ApplicationContextInitializer<?>> initializers) {
this.initializers = new ArrayList();
this.initializers.addAll(initializers);
}
这些初始化器后续会用于启动流程的一些回调,后面再分析
setListeners
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
跟上面设置初始化器比较类似,也是到spring.factories文件中找指定类,这次传入的类型是ApplicationListener
通过debug,发现一共有10个
同样是分布在spring-boot和spring-boot-autoconfigure包下
spring-boot下有9个
spring-boot-autoconfigure下有1个
实例化后存储在SpringApplication的listeners变量中
public void setListeners(Collection<? extends ApplicationListener<?>> listeners) {
this.listeners = new ArrayList();
this.listeners.addAll(listeners);
}
这些监听器后续会接收启动流程的一些事件,完成诸如装载配置文件的功能,同样后面再具体分析
推断应用主类
最后一行代码,主要是为了推断应用的主类
this.mainApplicationClass = this.deduceMainApplicationClass();
推断方式比较有意思,它构造了一个RunTimeException,然后获取它的调用栈,找到名字是main的方法,返回所在类的className
private Class<?> deduceMainApplicationClass() {
try {
StackTraceElement[] stackTrace = (new RuntimeException()).getStackTrace();
StackTraceElement[] var2 = stackTrace;
int var3 = stackTrace.length;
for(int var4 = 0; var4 < var3; ++var4) {
StackTraceElement stackTraceElement = var2[var4];
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
} catch (ClassNotFoundException var6) {
;
}
return null;
}
到此SpringApplication的初始化流程就简单的介绍完了,接下来就调用了run方法,进入启动流程,后续文章再继续分析
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return (new SpringApplication(primarySources)).run(args);
}