一. 源码剖析入口
(一)SpringBoot项目的mian函数(入口)
package com.lagou;
import com.lagou.config.EnableRegisterServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication//标注在类上说明这个类是`SpringBoot`的主配置类
@EnableRegisterServer
public class SpringBootMytestApplication{
public static void main(String[] args) {
SpringApplication.run(SpringBootMytestApplication.class, args);
}
}
(二)点进run方法
/**
* Static helper that can be used to run a {@link SpringApplication} from the
* specified source using default settings.
* @param primarySource the primary source to load
* @param args the application arguments (usually passed from a Java main method)
* @return the running {@link ApplicationContext}
*/
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
// 调用重载方法
return run(new Class<?>[] { primarySource }, args);
}
(三)继续进入run方法
/**
* 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) {
// 两件事:1.初始化SpringApplication 2.执行run方法
return new SpringApplication(primarySources).run(args);
}
以上代码有两个过程:1.初始化SpringApplication 2.执行run方法
1. 初始化 SpringApplication
继续查看源码,
SpringApplication
实例化过程,首先是进入带参数的构造方法,最终会看到两个参数的构造方法
/**
* 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 primarySources the primary bean sources
* @see #run(Class, String[])
* @see #SpringApplication(ResourceLoader, Class...)
* @see #setSources(Set)
*/
public SpringApplication(Class<?>... primarySources) {
this(null, primarySources);
}
/**
* 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;
//断言加载资源类不能为null
Assert.notNull(primarySources, "PrimarySources must not be null");
//将primarySources数组转换为List,最后放到LinkedHashSet集合中
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
//【1.1 推断应用类型,后面会根据类型初始化对应的环境。常用的一般都是servlet环境 】
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//【1.2 初始化classpath下 META-INF/spring.factories中已配置的ApplicationContextInitializer 】
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
//【1.3 初始化classpath下所有已配置的 ApplicationListener 】
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//【1.4 根据调用栈,推断出 main 方法的类名 】
this.mainApplicationClass = deduceMainApplicationClass();
}
(1)推断应用类型,deduceWebApplicationType.deduceFromClasspath()
点击进入WebApplicationType类的deduceFromClasspath()方法
package org.springframework.boot;
import org.springframework.util.ClassUtils;
/**
* An enumeration of possible types of web application.
*
* @author Andy Wilkinson
* @author Brian Clozel
* @since 2.0.0
*/
public enum WebApplicationType {
/**
* The application should not run as a web application and should not start an
* embedded web server.
*/
NONE,
/**
* The application should run as a servlet-based web application and should start an
* embedded servlet web server.
*/
SERVLET,
/**
* The application should run as a reactive web application and should start an
* embedded reactive web server.
*/
REACTIVE;
private static final String[] SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet",
"org.springframework.web.context.ConfigurableWebApplicationContext" };
private static final String WEBMVC_INDICATOR_CLASS =
"org.springframework.web."
+ "servlet.DispatcherServlet";
private static final String WEBFLUX_INDICATOR_CLASS =
"org.springframework.web."
+ "reactive.DispatcherHandler";
private static final String JERSEY_INDICATOR_CLASS =
"org.glassfish.jersey.servlet.ServletContainer";
private static final String SERVLET_APPLICATION_CONTEXT_CLASS = "org.springframework.web.context.WebApplicationContext";
private static final String REACTIVE_APPLICATION_CONTEXT_CLASS = "org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext";
/**
* 判断 应用的类型
* NONE: 应用程序不是web应用,也不应该用web服务器去启动
* SERVLET: 应用程序应作为基于servlet的web应用程序运行,并应启动嵌入式servlet web(tomcat)服务器。
* REACTIVE: 应用程序应作为 reactive web应用程序运行,并应启动嵌入式 reactive web服务器。
* @return
*/
static WebApplicationType deduceFromClasspath() {
//classpath下必须存在org.springframework.web.reactive.DispatcherHandler
if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
return WebApplicationType.REACTIVE;
}
for (String className : SERVLET_INDICATOR_CLASSES) {
//classpath环境下不存在javax.servlet.Servlet或者org.springframework.web.context.ConfigurableWebApplicationContext
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
return WebApplicationType.SERVLET;
}
}
返回类型是
WebApplicationType
的枚举类型,
WebApplicationType
有三个枚举,三个枚举的解释如其中注释
具体的判断逻辑如下:
WebApplicationType.REACTIVE classpath
下存在
org.springframework.web.reactive.DispatcherHandler
WebApplicationType.SERVLET classpath
下存在
javax.servlet.Servlet
或者
org.springframework.web.context.ConfigurableWebApplicationContext
WebApplicationType.NONE
不满足以上条件。
(2)初始化classpath下 META-INF/spring.factories中已配置的ApplicationContextInitializer
![](https://i-blog.csdnimg.cn/blog_migrate/efd5f20aa135453b438862c3d63e7f0f.png)
点击进入 getSpringFactoriesInstances方法
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
return getSpringFactoriesInstances(type, new Class<?>[] {});
}
/**
* 通过指定的classloader 从META-INF/spring.factories获取指定的Spring的工厂实例
* @param type
* @param parameterTypes
* @param args
* @param <T>
* @return
*/
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = getClassLoader();
// Use names and ensure unique to protect against duplicates
//通过指定的classLoader从 META-INF/spring.factories 的资源文件中,
//读取 key 为 type.getName() 的 value
Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
//创建工厂实例
List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
//对Spring工厂实例排序(org.springframework.core.annotation.Order注解指定的顺序)
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
![](https://i-blog.csdnimg.cn/blog_migrate/3922a4e8c0196905c26bd19fd9e95b59.png)
看看
getSpringFactoriesInstances
都干了什么,看源码,有一个方法很重要
loadFactoryNames()
这个方法很重要,这个方法是
spring-core
中提供的从
META-INF/spring.factories
中获取指定的类
(key
)的同一入口方法。
点击进入
loadFactoryNames
(
type
,
classLoader
)方法
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
String factoryTypeName = factoryType.getName();
return (List)loadSpringFactories(classLoader).getOrDefault(factoryTypeName, 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 factoryTypeName = ((String)entry.getKey()).trim();
String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
int var10 = var9.length;
for(int var11 = 0; var11 < var10; ++var11) {
String factoryImplementationName = var9[var11];
result.add(factoryTypeName, factoryImplementationName.trim());
}
}
}
cache.put(classLoader, result);
return result;
} catch (IOException var13) {
throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);
}
}
}
以上可见SpringFactoriesLoader类是解析所有Spring.factories实现。方法主要是loadFactoryNames()和loadSpringFactories()
回到SpringApplication类的SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources)构造方法,我们可以在如下图处打个断点,观察返回的集合中都获取了什么:
上面说了,是从classpath下 META-INF/spring.factories中获取,我们验证一下:
![](https://i-blog.csdnimg.cn/blog_migrate/d89830a32ed3e5519cefc5d49e614f31.png)
发现在上图所示的两个工程中找到了debug中看到的结果。
ApplicationContextInitializer
是
Spring
框架的类
,
这个类的主要目的就是在
ConfigurableApplicationContext
调用
refresh()
方法之前,回调这个类的
initialize
方法。
通过
ConfigurableApplicationContext
的实例获取容器的环境
Environment
,从而实现对配置文件的修改完善等工作。
(3)初始化classpath下所有已配置的 ApplicationListener
![](https://i-blog.csdnimg.cn/blog_migrate/309ca557eb4accb5a767bd2e90bcedcc.png)
ApplicationListener
的加载过程和上面的
ApplicationContextInitializer
类的加载过程是一样的。
不多说了,至于
ApplicationListener
是
spring
的事件监听器,典型的观察者模式,通过
ApplicationEvent
类和
ApplicationListener
接口,可以实现对
spring
容器全生命周期的监听,当然也可以自定义监听事件 。
总结
关于
SpringApplication
类的构造过程,到这里我们就梳理完了。纵观
SpringApplication
类的实例化过程,我们可以看到,合理的利用该类,我们能在
spring
容器创建之前做一些预备工作,和定制化的需
求。
比如,自定义
SpringBoot
的
Banner
,比如自定义事件监听器,再比如在容器
refresh
之前通过自定义ApplicationContextInitializer
修改配置一些配置或者获取指定的
bean
都是可以的。
2. 执行run方法
我们已经查看了
SpringApplication
类的实例化过程,这里开始执行
SpringBoot
启动流程中最重要的
部分
run
方法。点进run方法,通过
run
方法的剖析开启
SpringBoot整个的
启动流程:
/**
* Run the Spring application, creating and refreshing a new
* {@link ApplicationContext}.
* @param args the application arguments (usually passed from a Java main method)
* @return a running {@link ApplicationContext}
* 运行spring应用,并刷新一个新的 ApplicationContext(Spring的上下文)
* ConfigurableApplicationContext 是 ApplicationContext 接口的子接口。在 ApplicationContext
* 基础上增加了配置上下文的工具。 ConfigurableApplicationContext是容器的高级接口
*/
public ConfigurableApplicationContext run(String... args) {
//记录程序运行时间
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// ConfigurableApplicationContext Spring 的上下文
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
//【1、获取并启动监听器】
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//【2、构造应用上下文环境】
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
//处理需要忽略的Bean
configureIgnoreBeanInfo(environment);
//打印banner
Banner printedBanner = printBanner(environment);
///【3、初始化应用上下文】
context = createApplicationContext();
//实例化SpringBootExceptionReporter.class,用来支持报告关于启动的错误
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
//【4、刷新应用上下文前的准备阶段】
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//【5、刷新应用上下文】
refreshContext(context);
//【6、刷新应用上下文后的扩展接口】
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;
}
二. 第一步获取并启动监听器
事件机制在
Spring
是很重要的一部分内容,通过事件机制我们可以监听
Spring
容器中正在发生的一些事件,同样也可以自定义监听事件。
Spring
的事件为
Bean
和
Bean
之间的消息传递提供支持。当一个对象
处理完某种任务后,通知另外的对象进行某些处理,常用的场景有进行某些操作后发送通知,消息、邮件等情况。
点进getRunListeners(args)方法:
![](https://i-blog.csdnimg.cn/blog_migrate/072551e639da44964f2e16ea19ef9d4d.png)
private SpringApplicationRunListeners getRunListeners(String[] args) {
Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
// SpringApplicationRunListeners负责在SpringBoot启动的不同阶段,
// 广播出不同的消息, 传递给ApplicationListener监听器实现类。
return new SpringApplicationRunListeners(logger,
getSpringFactoriesInstances(
SpringApplicationRunListener.class, types, this, args));
}
在这里看到一个熟悉的方法:
getSpringFactoriesInstances()
,前面
已经详细介绍过该方法是怎么一步步的获取到
META-INF/spring.factories
中的指定的
key
的
value
,获取到以后怎么实例化类的。
回到
run
方法,
debug
这个代码
SpringApplicationRunListeners listeners = getRunListeners(args);
看一下获取的是哪个监听器:
![](https://i-blog.csdnimg.cn/blog_migrate/1e382f36bfd6520e22040256282d745d.png)
EventPublishingRunListener监听器是Spring容器的启动监听器。