Springboot启动流程详细分析
作者:起风哥 发布时间:2023-11-29 00:23:10
springboot启动是通过一个main方法启动的,代码如下
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
从该方法我们一路跟进去,进入SpringApplication的构造函数,我们可以看到如下代码primarySources,为我们从run方法塞进来的主类,而resourceLoader此处为null,是通过构造函数重载进来,意味着这里还有其它方式的用法,先绕过。
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容器类型是servlet 还是REACTIVE还是啥也不是即当前非web容器
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//此处进入springFacories的加载 即SpringFactoriesLoader,不过此处是过滤处所有ApplicationContextInitializer的子类
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
//从springFactories的缓存中再过滤处ApplicationListener 的子类
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
所以我们来看SpringFactoriesLoader中的loadSpringFactories方法,先获取资源路径META-INF/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 {
//classLoader 上一步传进来的为AppClassLoader,如果对classLoader不了解需要去看看java的类加载机制,以及双亲委托机制,此处的资源加载也是个双亲委托机制。
//此处如果appclassLoader不为null,那么遍历遍历这个classLoader所加载的包,中是否存在META-INF/spring.factories这个文件
//如果存在最终生成一个集合,然后遍历集合
Enumeration<URL> urls = (classLoader != null ?
classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
result = new LinkedMultiValueMap<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
//从集合中取出一个spring.factories文件
UrlResource resource = new UrlResource(url);
//读取对应文件内容,作为一个properties对象
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
//解析文件内容,并将之放入一个LinkedMultiValueMap中,key就是spring.factories中等号前面的部分,值是后面部分根据都好组成的list。并放入缓存备用,缓存的key为对应的classLoader
for (Map.Entry<?, ?> entry : properties.entrySet()) {
String factoryClassName = ((String) entry.getKey()).trim();
for (String factoryName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
result.add(factoryClassName, factoryName.trim());
}
}
}
cache.put(classLoader, result);
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
以上代码执行完成后形成的内容大概是这样的,key表示factoryClassName
result = new LinkedMultiValueMap<>();
list=new LinkList();
list.add("com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration");
list.add("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration")
result.put("org.springframework.boot.autoconfigure.EnableAutoConfiguration",list);
所以此时回退到这个方法setInitializers((Collection)
getSpringFactoriesInstances(ApplicationContextInitializer.class));
就是从遍历出来的所有的这些内容中获取出key为org.springframework.context.ApplicationContextInitializer 的集合
设置该当前类的initializers集合,后面的Listeners 集合也是一样的过程。只不过,后一次获取是从上一次的缓存中取的。
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}
设置完initializer和listener集合后,进行主函数推断
接着看代码,此处对主函数的推断非常的巧妙,就是利用虚拟机运行时已被入栈的所有链路一路追踪到方法名为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 对象new出来了,然后接着执行它的run方法,先总结下以上代码干了几个事情
this.primarySources 设置了主类集合
this.webApplicationType 设置了web容器类型
setInitializers 设置了ApplicationContextInitializer
setListeners 设置了ApplicationListener
mainApplicationClass 设置了入口类
加载并且解析了所有的spring.factories文件并缓存起来,注意此时只是解析成属性。
我们发现一个奇怪的现象既然已经有了this.primarySources 为什么还要来个mainApplicationClass呢?mainApplicationClass目前看来除了日志打印以及banner之外没有什么其它作用。
接着看run方法
public ConfigurableApplicationContext run(String... args) {
//计时器,不管它
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
//告诉程序当前为无头模式,没有外设,如果需要调用外设接口需要你自己模拟,这些内容再awt包中做了,所以你只要告诉它有没有外设就可以了
configureHeadlessProperty();
//继续从spring.factories中获取对应的对象,此时listeners中有一个默认实现EventPublishingRunListener,如有需要这里是可进行扩展
SpringApplicationRunListeners listeners = getRunListeners(args);
//遍历所有的listeners并调用它的starting方法,广播启动过程中的事件,注意这里是个广播器不是 * ,名字有点不好理解,实现了
//ApplicationListener的接口就接收到对应事件之后执行对应操作,而我们前面也有设置了个listeners集合,为ApplicationListener
//此处名字起的让人容易误解,明明是个广播器非要叫RunListener
listeners.starting();
try {
//进行控制台参数解析,具体如何解析,此处不展开,后续对配置文件解析的文章在详细介绍
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
//此处配置个内省beanInfo时是否缓存的开关,true就缓存,false,就不缓存
configureIgnoreBeanInfo(environment);
//打印banner,这个不介绍了比较简单的东西
Banner printedBanner = printBanner(environment);
//此处开始创建容器,根据给定的容器类型也就是上面获取到的webApplicationType创建对应的容器
//servlet :org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
//reactive:org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext
//default: org.springframework.context.annotation.AnnotationConfigApplicationContext 非web容器
context = createApplicationContext();
//异常解析器,如果出现异常了,会在被catch起来,然后通过解析器链进行解析。这个也是从spring.factories中获取的
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
//上面创建了容器,这边对容器做一些初始化操作
//1、设置环境变量env
//2、执行postProcessApplicationContext 准备beanNameGenerator,resourceLoader,ApplicationConversionService
//3、调用前面获取到的ApplicationContextInitializer
//4、广播容器准备完成事件
//5、添加了一个制定的单例就是banner打印用的
//6、在加载前,设置是否允许bean被覆盖属性,默认false
//7、开始加载,入口为main函数传入的primarySources,先创建个BeanDefinitionLoader,并将第二步准备的实例设置给他,
//最后由BeanDefinitionLoader.load()承当所有的加载动作,加载过程也很长,先按下不表。
//8、广播容器加载事件
//到此容器准备完成
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
//开始执行spring的refresh方法,此处不多介绍了
refreshContext(context);
//容器refresh完成后留了个扩展,也不知道是不是扩展,这个方法需要去自定义启动类,有点奇怪
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
//然后广播启动完成事件
listeners.started(context);
//最后执行所有的runners,也就是实现了ApplicationRunner接口的类是最后执行,所以此时你可以做一些其它的动作,比如注册到注册中心,比如启动netty等等。
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;
}
上述代码中在prepareContext阶段完成了第一阶段的beanDefinition注册,此处仅注册了第一bean 通过主类传进去的那个类。之后再refresh阶段,通过解析该类进行第二轮的beandefinition注册。这一部分属于spring-context的内容了。
在refresh阶段,因为主类作为一个配置类,自然也是需要进行一轮解析的,所以接下来的步骤就是解析@SpringbootApplication,此注解为一个复合注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
内容解析:
@SpringBootConfiguration 等同于@Configuration
@EnableAutoConfiguration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
此处导入了一个AutoConfigurationImportSelector ,同时还通过@AutoConfigurationPackage导入了一个AutoConfigurationPackages.Registrar.class
接下来是一个@ComponentScan注解
而我们知道在spring的配置类(单一类)的解析过程中的顺序是
先解析Component系列的注解
再解析@PropertySource
接着解析@ComponentScan与@ComponentScans注解
接着解析@Import
接着解析ImportResource
最后解析@Bean注解
而再Import中又分为几种类型
ImportSelector
DeferredImportSelector
ImportBeanDefinitionRegistrar
普通的import类
他们的加载顺序为,普通的类–>importSelector–deferredImportSelector–>ImportResource–>ImportBeanDefinitionRegistrar
综上所述spring.factories声明的配置类看来也不是垫底解析的,所以如果有遇到需要顺序的场景可以参照这个顺序来声明即可。
来源:https://blog.csdn.net/a807719447/article/details/128398469


猜你喜欢
- 类锁和对象锁是否会冲突?对象锁和私有锁是否会冲突?通过实例来进行说明。一、相关约定为了明确后文的描述,先对本文涉及到的锁的相关定义作如下约定
- 1、概述传统的Android开发架构一般是MVC模式,Model:业务逻辑和实体模型View:对应于布局文件Controllor:对应于Ac
- 目录1、先创建对应相关操作的注解1.1 bTable 标识表1.2 DbPrimaryKey 标识主键1.3 DbFil
- C#的FileInfo类提供了与File类相同的功能,不同的是FileInfo提供的都是成员方法,使用示例如下所示:1、读文件://创建只读
- 在Struts2中Action部分,也就是Controller层采用了低侵入的方式。为什么这么说?这是因为在Struts2中action类并
- 可以指定编码如:utf-8来写入和读取文件。如果文件编码未知,可以通过该方法先得到文件的编码后再指定正确的编码来读取,否则会出现文件乱码问题
- 目录实现基础_routeNamed_flushHistoryUpdatesaddpushpopremove总结整个 flutter 应用的运
- 1 编程语言简介编程语言(programming language)可以简单的理解为一种计算机和人都能识别的语言。一种计算机语言让程序员能够
- 1.设计思路,使用VersionCode定义为版本升级参数。android为我们定义版本提供了2个属性:<manifest packa
- 0x001 算数运算符 int num1 = 1, num2 = 2; System.o
- https://www.jb51.net/article/152879.htm上节,我们明白了proc文件系统的作用,接下来我们在已经写好的
- Java实现远程控制技术java自带的java.net.和java.awt.robot. 的混合可以用于实现通过网络对另一台计算机的远程控制
- 代理对象的生成方法是:Proxy.newProxyInstance(...) ,进入这个方法内部,一步一步往下走会发现会调用ProxyGen
- WPF下给ComboBox设置绑定字段时可通过如下设置:combobox.SelectedValuePath = "编号"
- 目录Static基本规则:1. static方法2. static变量3. static代码块4. static内部类5. static静态
- 线程同步的概念由于同一个进程的多个线程共享同一块存储空间,在带来方便的同时,也会带来访问冲突的问题:举例:public class Runn
- MyBatisMyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC
- 本文实例为大家分享了Unity实现俄罗斯方块第2部分,供大家参考,具体内容如下代码部分1. 实现物体自由降落(在有关于物体的脚本中编写)1)
- 最近工作遇到一个需求,需要下载excel模板,编辑后上传解析存储到数据库。因此为了更好的理解公司框架,我就自己先用spring mvc实现了
- choose标签用法choose 标签是按顺序判断其内部 when 标签中的 test 条件出否成立,如果有一个成立,则 choose 结束