Springboot启动原理
public static void main(String[] args) {
//xxx.class:主配置类,(可以传多个)
SpringApplication.run(xxx.class, args);
}
1. 从run方法开始,创建SpringApplication,然后再调用run方法
/**
* ConfigurableApplicationContext(可配置的应用程序上下文)
*/
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
//调用下面的run方法
return run(new Class[]{primarySource}, args);
}
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
//primarySources:主配置类
return (new SpringApplication(primarySources)).run(args);
}
2. 创建SpringApplication
public SpringApplication(Class<?>... primarySources) {
//调用下面构造方法
this((ResourceLoader) null, primarySources);
}
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
//获取类加载器
this.resourceLoader = resourceLoader;
//查看类加载器是否为空
Assert.notNull(primarySources, "PrimarySources must not be null");
// 保存主配置类的信息到一个哈希链表集合中,方便查询调用增删
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
//获取当前应用的类型,是不是web应用,见2.1
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//从类路径下找到META‐INF/spring.factories配置的所有ApplicationContextInitializer;然后保存起来,见2.2
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
//从类路径下找到META‐INF/spring.factories配置的所有spring.ApplicationListener;然后保存起来,原理同上
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//从多个SpringApplication中找到有main方法的主SpringApplication(在调run方法的时候是可以传递多个配置类的)
//只记录有main方法的类名,以便下一步的run
this.mainApplicationClass = deduceMainApplicationClass();
}
2.1 deduceFromClasspath
static WebApplicationType deduceFromClasspath() {
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) {
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
return WebApplicationType.SERVLET;
}
2.2 getSpringFactoriesInstances
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = getClassLoader();
// Use names and ensure unique to protect against duplicates
// 配置的所有ApplicationContextInitializer等分别到一个集合中以便查询使用,其中loadFactoryNames方法从类路径下找到META‐INF/spring.factories中传入的parameterTypes
Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
// 实例化传入的类
List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
// 排序以便提高针对他执行操作的效率
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
2.3 deduceMainApplicationClass
private Class<?> deduceMainApplicationClass() {
try {
// 查询当前的虚拟机的当前线程的StackTrace信息
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
// 查看当前线程中已加载的类中有没有main方法
if ("main".equals(stackTraceElement.getMethodName())) {
//有则返回该类的类名
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}
StackTrace简述
1 StackTrace用栈的形式保存了方法的调用信息.
2 怎么获取这些调用信息呢?
可用Thread.currentThread().getStackTrace()方法得到当前线程的StackTrace信息.该方法返回的是一个StackTraceElement数组.
3 该StackTraceElement数组就是StackTrace中的内容.
4 遍历该StackTraceElement数组.就可以看到方法间的调用流程.
比如线程中methodA调用了methodB那么methodA先入栈methodB再入栈.
5 在StackTraceElement数组下标为2的元素中保存了当前方法的所属文件名,当前方法所属的类名,以及该方法的名字
除此以外还可以获取方法调用的行数.
6 在StackTraceElement数组下标为3的元素中保存了当前方法的调用者的信息和它调用时的代码行数.
3. 调用SpringApplication对象的run方法
3. 调用SpringApplication对象的run方法
Apllication总体流程
SpringApplication的run方法的实现是我们本次旅程的主要线路,该方法的主要流程大体可以归纳如下:
1) 如果我们使用的是SpringApplication的静态run方法,那么,这个方法里面首先要创建一个SpringApplication对象实例,然后调用这个创建好的SpringApplication的实例方法。在SpringApplication实例初始化的时候,它会提前做几件事情:
- 根据classpath里面是否存在某个特征类(org.springframework.web.context.ConfigurableWebApplicationContext)来决定是否应该创建一个为Web应用使用的ApplicationContext类型。
- 使用SpringFactoriesLoader在应用的classpath中查找并加载所有可用的ApplicationContextInitializer。
- 使用SpringFactoriesLoader在应用的classpath中查找并加载所有可用的ApplicationListener。
- 推断并设置main方法的定义类。
2) SpringApplication实例初始化完成并且完成设置后,就开始执行run方法的逻辑了,方法执行伊始,首先遍历执行所有通过SpringFactoriesLoader可以查找到并加载的SpringApplicationRunListener。调用它们的started()方法,告诉这些SpringApplicationRunListener,“嘿,SpringBoot应用要开始执行咯!”。
3) 创建并配置当前Spring Boot应用将要使用的Environment(包括配置要使用的PropertySource以及Profile)。
4) 遍历调用所有SpringApplicationRunListener的environmentPrepared()的方法,告诉他们:“当前SpringBoot应用使用的Environment准备好了咯!”。
5) 如果SpringApplication的showBanner属性被设置为true,则打印banner。
6) 根据用户是否明确设置了applicationContextClass类型以及初始化阶段的推断结果,决定该为当前SpringBoot应用创建什么类型的ApplicationContext并创建完成,然后根据条件决定是否添加ShutdownHook,决定是否使用自定义的BeanNameGenerator,决定是否使用自定义的ResourceLoader,当然,最重要的,将之前准备好的Environment设置给创建好的ApplicationContext使用。
7) ApplicationContext创建好之后,SpringApplication会再次借助Spring-FactoriesLoader,查找并加载classpath中所有可用的ApplicationContext-Initializer,然后遍历调用这些ApplicationContextInitializer的initialize(applicationContext)方法来对已经创建好的ApplicationContext进行进一步的处理。
8) 会调用SpringApplication的prepareContext方法,其中会遍历调用所有SpringApplicationRunListener的contextPrepared()方法。
9)将之前通过@EnableAutoConfiguration获取的所有配置以及其他形式的IoC容器配置加载到已经准备完毕的ApplicationContext。
10)遍历调用所有SpringApplicationRunListener的contextLoaded()方法。
11)接着便是SpringApplication的afterRefresh方法,调用ApplicationContext的refresh()方法,完成IoC容器可用的最后一道工序。
12) 查找当前ApplicationContext中是否注册有CommandLineRunner,如果有,则遍历执行它们。
13) 正常情况下,遍历执行SpringApplicationRunListener的finished()方法、(如果整个过程出现异常,则依然调用所有SpringApplicationRunListener的finished()方法,只不过这种情况下会将异常信息一并传入处理)
public ConfigurableApplicationContext run(String... args) {
//Simple stop watch, allowing for timing of a number of tasks, exposing totalrunning time and running time for each named task.简单来说是创建ioc容器的计时器
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//声明IOC容器
ConfigurableApplicationContext context = null;
//异常报告存储列表
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
//加载图形化配置
this.configureHeadlessProperty();
//从类路径下META‐INF/spring.factories获取SpringApplicationRunListeners,原理同2中获取ApplicationContextInitializer和ApplicationListener
SpringApplicationRunListeners listeners = this.getRunListeners(args);
//遍历上一步获取的所有SpringApplicationRunListener,调用其starting方法
listeners.starting();
Collection exceptionReporters;
try {
//封装命令行
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//准备环境,把上面获取到的SpringApplicationRunListeners传过去,见3.1
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
//打印Banner,就是控制台那个Spring字符画
Banner printedBanner = this.printBanner(environment);
//根据当前环境利用反射创建IOC容器,见3.2
context = this.createApplicationContext();
//从类路径下META‐INF/spring.factories获取SpringBootExceptionReporter,原理同2中获取ApplicationContextInitializer和ApplicationListener
exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
//准备IOC容器,见3.3
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//刷新IOC容器,可查看配置嵌入式Servlet容器原理,所有的@Configuration和@AutoConfigutation等Bean对象全在此时加入容器中,并依据不同的选项创建了不同功能如服务器/数据库等组件。见3.4
//可以说@SpringbootApplication中自动扫描包和Autoconfiguration也是在此时进行的
this.refreshContext(context);
//这是一个空方法
this.afterRefresh(context, applicationArguments);
//停止计时,打印时间
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
//调用所有SpringApplicationRunListener的started方法
listeners.started(context);
//见3.5 ,从ioc容器中获取所有的ApplicationRunner和CommandLineRunner进行回调ApplicationRunner先回调,CommandLineRunner再回调。
this.callRunners(context, applicationArguments);
} catch (Throwable var10) {
this.handleRunFailure(context, var10, exceptionReporters, listeners);
throw new IllegalStateException(var10);
}
try {
//调用所有SpringApplicationRunListener的running方法
listeners.running(context);
//返回创建好的ioc容器,启动完成
return context;
} catch (Throwable var9) {
this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var9);
}
}
3.1 prepareEnvironment
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) {
//获取或者创建环境,有则获取,无则创建
ConfigurableEnvironment environment = this.getOrCreateEnvironment();
//配置环境
this.configureEnvironment((ConfigurableEnvironment)environment, applicationArguments.getSourceArgs());
ConfigurationPropertySources.attach((Environment)environment);
//创建环境完成后,ApplicationContext创建前,调用前面获取的所有SpringApplicationRunListener的environmentPrepared方法,读取配置文件使之生效
listeners.environmentPrepared((ConfigurableEnvironment)environment);
// 环境搭建好后,需依据他改变Apllication的参数,将enviroment的信息放置到Binder中,再由Binder依据不同的条件将“spring.main”SpringApplication更改为不同的环境,为后面context的创建搭建环境
//为什么boot要这样做,其实咱们启动一个boot的时候并不是一定只有一个Application且用main方式启动。这样子我们可以读取souces配置多的Application
this.bindToSpringApplication((ConfigurableEnvironment)environment);
if (!this.isCustomEnvironment) {
environment = (new EnvironmentConverter(this.getClassLoader())).convertEnvironmentIfNecessary((ConfigurableEnvironment)environment, this.deduceEnvironmentClass());
}
ConfigurationPropertySources.attach((Environment)environment);
//回到3,将创建好的environment返回
return (ConfigurableEnvironment)environment;
}
3.2 createApplicationContext
protected ConfigurableApplicationContext createApplicationContext() {
//获取当前Application中ioc容器类
Class<?> contextClass = this.applicationContextClass;
//若没有则依据该应用是否为web应用而创建相应的ioc容器
//除非为其传入applicationContext,不然Application的默认构造方法并不会创建ioc容器
if (contextClass == null) {
try {
switch(this.webApplicationType) {
case SERVLET:
contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");
break;
case REACTIVE:
contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");
break;
default:
contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
}
} catch (ClassNotFoundException var3) {
throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
}
}
//用bean工具类实例化ioc容器对象并返回。回到3
return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
}
3.3 prepareContext
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
//将创建好的环境放到IOC容器中
context.setEnvironment(environment);
//处理一些组件,没有实现postProcessA接口
this.postProcessApplicationContext(context);
//获取所有的ApplicationContextInitializer调用其initialize方法,这些ApplicationContextInitializer就是在2步骤中获取的,见3.3.1
this.applyInitializers(context);
//回调所有的SpringApplicationRunListener的contextPrepared方法,这些SpringApplicationRunListeners是在步骤3中获取的
listeners.contextPrepared(context);
//打印日志
if (this.logStartupInfo) {
this.logStartupInfo(context.getParent() == null);
this.logStartupProfileInfo(context);
}
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
//将一些applicationArguments注册成容器工厂中的单例对象
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory)beanFactory).setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
//若是延迟加载,则在ioc容器中加入LazyInitializationBeanFactoryPostProcessor,
if (this.lazyInitialization) {
context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
}
//获取所有报告primarySources在内的所有source
Set<Object> sources = this.getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
//加载容器
this.load(context, sources.toArray(new Object[0]));
//回调所有的SpringApplicationRunListener的contextLoaded方法
listeners.contextLoaded(context);
}
3.3.1 applyInitializers
protected void applyInitializers(ConfigurableApplicationContext context) {
Iterator var2 = this.getInitializers().iterator();
while(var2.hasNext()) {
//将之前的所有的ApplicationContextInitializer遍历
ApplicationContextInitializer initializer = (ApplicationContextInitializer)var2.next();
//解析查看之前从spring.factories调用的ApplicationContextInitializer是否能被ioc容器调用
Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class);
Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
//可以调用则对ioc容器进行初始化(还没加载我们自己配置的bean和AutoConfiguration那些)
initializer.initialize(context);
}
}//返回3.3
3.4 refreshment(context)
@Override
//详情见内置Servlet的启动原理,最后是用ApplicationContext的实现类的refresh()方法,若是web Application则为ServletWebServerApplicationContext
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
3.5 callRunners
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList();
//将ioc容器中的的ApplicationRunner和CommandLineRunner(),在创建ioc容器时创建的
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
Iterator var4 = (new LinkedHashSet(runners)).iterator();
//调用ApplicationRunner和CommandLineRunner的run方法
while(var4.hasNext()) {
Object runner = var4.next();
if (runner instanceof ApplicationRunner) {
this.callRunner((ApplicationRunner)runner, args);
}
if (runner instanceof CommandLineRunner) {
this.callRunner((CommandLineRunner)runner, args);
}
}
}
配置在META-INF/spring.factories
- ApplicationContextInitializer(在我们将enviroment绑定到application后可以用来创建不同类型的context)
- SpringApplicationRunListener(在Application 创建/运行/销毁等进行一些我们想要的特殊配置)
只需要放在ioc容器中
- ApplicationRunner(加载没有在ApplicationContext中的bean时让bean能加载)
- CommandLineRunner(命令行执行器)
Application初始化组件测试
-
创建
ApplicationContextInitializer
和SpringApplicationRunListener
的实现类,并在META-INF/spring.factories文件中配置public class TestApplicationContextInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { System.out.println("TestApplicationContextInitializer.initialize"); } }
public class TestSpringApplicationRunListener implements SpringApplicationRunListener { @Override public void starting() { System.out.println("TestSpringApplicationRunListener.starting"); } @Override public void environmentPrepared(ConfigurableEnvironment environment) { System.out.println("TestSpringApplicationRunListener.environmentPrepared"); } @Override public void contextPrepared(ConfigurableApplicationContext context) { System.out.println("TestSpringApplicationRunListener.contextPrepared"); } @Override public void contextLoaded(ConfigurableApplicationContext context) { System.out.println("TestSpringApplicationRunListener.contextLoaded"); } @Override public void started(ConfigurableApplicationContext context) { System.out.println("TestSpringApplicationRunListener.started"); } @Override public void running(ConfigurableApplicationContext context) { System.out.println("TestSpringApplicationRunListener.running"); } @Override public void failed(ConfigurableApplicationContext context, Throwable exception) { System.out.println("TestSpringApplicationRunListener.failed"); } }
org.springframework.context.ApplicationContextInitializer= cn.clboy.springbootprocess.init.TestApplicationContextInitializer org.springframework.boot.SpringApplicationRunListener= cn.clboy.springbootprocess.init.TestSpringApplicationRunListener
启动报错:说是没有找到带org.springframework.boot.SpringApplication和String数组类型参数的构造器,给TestSpringApplicationRunListener添加这样的构造器
public TestSpringApplicationRunListener(SpringApplication application,String[] args) { }
-
创建
ApplicationRunner
实现类和CommandLineRunner
实现类,因为是从ioc容器完成创建后中提取存放在里面的这两个Runner,因此可以直接添加到容器中,最后callRunner使用@Component public class TestApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("TestApplicationRunner.run --->"+args); } }
@Component public class TestCommandLineRunn implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("TestCommandLineRunn.runt --->"+ Arrays.toString(args)); } }