前言
Springboot应用在启动的时候分为两步:首先生成 SpringApplication 对象 ,运行 SpringApplication 的 run 方法,下面一一看一下每一步具体都干了什么
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}
创建 SpringApplication 对象
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应用
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//从类路径下找到META-INF/spring.factories配置的所有ApplicationContextInitializer;然后保存起来
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
//从类路径下找到ETA-INF/spring.factories配置的所有ApplicationListener
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//从多个配置类中找到有main方法的主配置类
this.mainApplicationClass = deduceMainApplicationClass();
}
其中从类路径下获取到META-INF/spring.factories配置的所有ApplicationContextInitializer和ApplicationListener的具体代码如下
public final class SpringFactoriesLoader {
/**spring.factories的位置*/
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
private static final Log logger = LogFactory.getLog(SpringFactoriesLoader.class);
/**
* 缓存扫描后的结果, 注意这个cache是static修饰的,说明是多个实例共享的
* 其中MultiValueMap的key就是spring.factories中的key(比如org.springframework.boot.autoconfigure.EnableAutoConfiguration),
* 其值就是key对应的value以逗号分隔后得到的List集合(这里用到了MultiValueMap,他是guava的一键多值map, 类似Map<String, List<String>>)
*/
private static final Map<ClassLoader, MultiValueMap<String, String>> cache = new ConcurrentReferenceHashMap<>();
private SpringFactoriesLoader() {
}
/**
* AutoConfigurationImportSelector及应用的初始化器和监听器里最终调用的就是这个方法,
* 这里的factoryType是EnableAutoConfiguration.class、ApplicationContextInitializer.class、或ApplicationListener.class
* classLoader是AutoConfigurationImportSelector、ApplicationContextInitializer、或ApplicationListener里的beanClassLoader
*/
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
String factoryTypeName = factoryType.getName();
return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}
/**
* 加载 spring.factories文件的核心实现
*/
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
// 先从缓存获取,如果获取到了说明之前已经被加载过
MultiValueMap<String, String> result = cache.get(classLoader);
if (result != null) {
return result;
}
try {
// 找到所有jar中的spring.factories文件的地址
Enumeration<URL> urls = (classLoader != null ?
classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
result = new LinkedMultiValueMap<>();
// 循环处理每一个spring.factories文件
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
// 加载spring.factories文件中的内容到Properties对象中
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
// 遍历spring.factories内容中的所有的键值对
for (Map.Entry<?, ?> entry : properties.entrySet()) {
// 获得spring.factories内容中的key(比如org.springframework.boot.autoconfigure.EnableAutoConfiguratio)
String factoryTypeName = ((String) entry.getKey()).trim();
// 获取value, 然后按英文逗号(,)分割得到value数组并遍历
for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
// 存储结果到上面的多值Map中(MultiValueMap<String, String>)
result.add(factoryTypeName, factoryImplementationName.trim());
}
}
}
cache.put(classLoader, result);
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
}
运行run方法
public ConfigurableApplicationContext run(String... args) {
//开始停止的监听
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//声明一个可配置的ioc容器
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
//配置awt相关的东西
configureHeadlessProperty();
//获取SpringApplicationRunListeners;从类路径下META-INF/spring.factories
SpringApplicationRunListeners listeners = getRunListeners(args);
//回调所有的获取SpringApplicationRunListener.starting()方法
listeners.starting();
try {
//封装命令行参数
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
//准备环境
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
//创建环境完成后回调SpringApplicationRunListener.environmentPrepared();表示环境准备完成
Banner printedBanner = printBanner(environment);
//创建ApplicationContext;决定创建web的ioc还是普通的ioc,
//通过反射创建ioc容器((ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);)
context = createApplicationContext();
//出现异常之后做异常分析报告
analyzers = new FailureAnalyzers(context);
//准备上下文环境;将environment保存到ioc中;而且applyInitializers();
//applyInitializers():回调之前保存的所有的ApplicationContextInitializer的initialize方法
//回调所有的SpringApplicationRunListener的contextPrepared();
//
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
//prepareContext运行完成以后回调所有的SpringApplicationRunListener的contextLoaded();
//刷新容器;ioc容器初始化(如果是web应用还会创建嵌入式的Tomcat);Spring注解版
//扫描,创建,加载所有组件的地方;(配置类,组件,自动配置)
refreshContext(context);
//从ioc容器中获取所有的ApplicationRunner和CommandLineRunner进行回调
//ApplicationRunner先回调,CommandLineRunner再回调
afterRefresh(context, applicationArguments);
//所有的SpringApplicationRunListener回调finished方法
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
//整个SpringBoot应用启动完成以后返回启动的ioc容器;
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}
几个重要的事件回调机制
配置在META-INF/spring.factories
ApplicationContextInitializer
SpringApplicationRunListener
只需要放在ioc容器中
ApplicationRunner
CommandLineRunner
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持小牛知识库。
本文的目的是分析 MOSN 的启动流程。基于 mosn 版本 v0.4.0,commit 为: dc35c8fc95435a47e6393db1c79dd9f60f7eb898 MOSN 简介 MOSN 是一款使用 Go 语言开发的网络代理软件,作为云原生的网络数据平面,旨在为服务提供多协议,模块化,智能化,安全的代理能力。 MOSN 在基于 Kubernetes 的 service mesh 中
本文向大家介绍Spring启动流程refresh()源码深入解析,包括了Spring启动流程refresh()源码深入解析的使用技巧和注意事项,需要的朋友参考一下 一、Spring容器的refresh() spring version:4.3.12 ,尚硅谷Spring注解驱动开发—源码部分 1 、prepareRefresh()刷新前的预处理; 2、 obtainFreshBeanFacto
在一开始,就介绍过,Logstash 对日志的处理,从 input 到 output,就像在 Linux 命令行上的管道操作一样。事实上,在 Logstash 中,对此有一个专门的名词,叫 Pipeline。 Pipeline 的代码加载路径如下: bin/logstash -> logstash-core/lib/logstash/runner.rb -> logstash-core/lib/l
使用spring-boot时,一切工作都很好。尽管如此,在spring-boot中已删除了注释和。我试图将代码重构为新版本,但我做不到。对于以下测试,我的应用程序在测试之前没有启动,http://localhost:8080返回404: 如何重构测试以使其在Spring-Boot1.5中工作?
本文向大家介绍SpringBoot Tomcat启动实例代码详解,包括了SpringBoot Tomcat启动实例代码详解的使用技巧和注意事项,需要的朋友参考一下 废话不多了,具体内容如下所示: 注意: 启动类放在项目的包的最外层最好,这样可以扫描到所有的包路径。 controller: pom 注意:如果想用tomcat7启动要制定你的tomcat版本号。 项目 总结 以上所述是小编给大家介绍的
【分布式事务Seata源码解读一】Server端启动流程 实现分布式事务的核心要点: 事务的持久化,事务所处的各种状态事务参与方的各种状态都需要持久化,当实例宕机时才能基于持久化的数据对事务回滚或提交,实现最终一致性 定时对超时未完成事务的处理(继续尝试提交或回滚),即通过重试机制实现事务的最终一致性 分布式事务的跨服务实例传播,当分布式事务跨多个实例时需要实现事务的传播,一般需要适配不同的rpc
【分布式事务Seata源码解读二】Client端启动流程 本文从源码的角度分析一下AT模式下Client端启动流程,所谓的Client端,即业务应用方。分布式事务分为三个模块:TC、TM、RM。其中TC位于seata-server端,而TM、RM通过SDK的方式运行在client端。 下图展示了Seata官方Demo的一个分布式事务场景,分为如下几个微服务,共同实现了一个下订单、扣库存、扣余额的分
我的程序编译了所有内容,我没有出错,但我实际上期望tomcat应该永久在端口8080上。输出中也没有Spring。在另一个项目中,我做的一切都很好。谢谢你帮助我。 我的父母: 我的tarter.class: 我的Starter-Pom: 控制台输出: 然后什么都不会发生了。谢谢你的帮助。