当前位置: 首页 > news >正文

SpringBoot 的启动原理

SpringBoot 的启动核心是通过SpringApplication.run()方法完成,其本质是对 Spring 框架的封装与扩展,实现了 "自动配置"、"内嵌容器" 等核心特性。下面结合源码分析其启动过程:

一、启动入口:SpringApplication.run()

SpringBoot 应用的启动入口是主类的main方法,核心调用SpringApplication.run(主类.class, args),例如:

java运行

@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args); // 启动核心}
}

SpringApplication.run()是一个静态方法,内部会先创建SpringApplication实例,再调用其run(args)方法,源码简化如下:

java运行

public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {return run(new Class<?>[] { primarySource }, args);
}public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {// 1. 创建SpringApplication实例  2. 调用实例的run方法return new SpringApplication(primarySources).run(args);
}

二、SpringApplication实例初始化

SpringApplication的构造方法会完成初始化工作,核心是确定应用类型加载初始化器加载监听器,源码关键逻辑如下:

java运行

public SpringApplication(Class<?>... primarySources) {this(null, primarySources);
}public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {this.resourceLoader = resourceLoader;this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));// 1. 确定应用类型(Servlet/Reactive/普通)this.webApplicationType = WebApplicationType.deduceFromClasspath();// 2. 加载初始化器(ApplicationContextInitializer)setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));// 3. 加载监听器(ApplicationListener)setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));// 4. 确定主类(从main方法所在类推断)this.mainApplicationClass = deduceMainApplicationClass();
}
关键步骤解析:
  1. 确定应用类型WebApplicationType.deduceFromClasspath()通过判断 classpath 中是否存在特定类(如ServletReactiveWebServerFactory),确定应用是:

    • SERVLET(传统 Web 应用,依赖 Servlet API)
    • REACTIVE(响应式 Web 应用,依赖 Spring WebFlux)
    • NONE(非 Web 应用)
  2. 加载初始化器和监听器:核心是getSpringFactoriesInstances()方法,通过Spring 的 SPI 机制(Service Provider Interface),从类路径下的META-INF/spring.factories文件中加载配置的初始化器(ApplicationContextInitializer)和监听器(ApplicationListener)。例如,spring.factories中可能包含:

    properties

    org.springframework.context.ApplicationContextInitializer=\
    org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
    org.springframework.boot.context.ContextIdApplicationContextInitializer
    

三、SpringApplication.run(args)核心流程

run()方法是启动的核心,可分为准备阶段上下文创建与刷新启动完成三个阶段,源码简化如下:

java运行

public ConfigurableApplicationContext run(String... args) {StopWatch stopWatch = new StopWatch();stopWatch.start(); // 计时开始// 1. 初始化运行监听器和应用上下文ConfigurableApplicationContext context = null;Collection<SpringApplicationRunListener> listeners = getRunListeners(args);listeners.starting(); // 发布启动事件(ApplicationStartingEvent)try {// 2. 准备环境(配置、参数等)ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);configureIgnoreBeanInfo(environment);// 3. 打印Banner(控制台图标)Banner printedBanner = printBanner(environment);// 4. 创建应用上下文(根据应用类型)context = createApplicationContext();// 5. 准备上下文(关联环境、注册主类等)prepareContext(context, environment, listeners, applicationArguments, printedBanner);// 6. 刷新上下文(核心!Spring容器初始化+SpringBoot扩展)refreshContext(context);// 7. 刷新后的操作(空实现,供扩展)afterRefresh(context, applicationArguments);stopWatch.stop(); // 计时结束listeners.started(context); // 发布启动完成事件(ApplicationStartedEvent)// 8. 执行Runner(CommandLineRunner/ApplicationRunner)callRunners(context, applicationArguments);listeners.running(context); // 发布运行中事件(ApplicationReadyEvent)} catch (Throwable ex) {handleRunFailure(context, ex, listeners); // 处理启动失败throw new IllegalStateException(ex);}return context;
}
关键步骤详解:
1. 准备环境(prepareEnvironment
  • 作用:初始化应用环境(包含配置文件、系统变量、命令行参数等)。
  • 流程:
    • 创建ConfigurableEnvironment(根据应用类型,如StandardServletEnvironment)。
    • 加载配置(application.properties/yml、系统变量、args参数等)。
    • 发布ApplicationEnvironmentPreparedEvent事件,监听器(如配置文件加载器)会处理该事件。
2. 创建应用上下文(createApplicationContext
  • 作用:根据应用类型创建对应的ApplicationContext(Spring 容器的核心)。
  • 逻辑:

    java运行

    protected ConfigurableApplicationContext createApplicationContext() {Class<?> contextClass = this.webApplicationType.getApplicationContextClass();return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
    }
    
    • SERVLET应用:创建AnnotationConfigServletWebServerApplicationContext
    • REACTIVE应用:创建AnnotationConfigReactiveWebServerApplicationContext
    • 非 Web 应用:创建AnnotationConfigApplicationContext
3. 准备上下文(prepareContext
  • 作用:将环境、监听器、主类等关联到上下文,并加载主类作为配置类。
  • 关键逻辑:
    • 关联环境:context.setEnvironment(environment)
    • 执行初始化器:applyInitializers(context)(初始化器对上下文进行预处理)
    • 发布ApplicationContextInitializedEvent事件
    • 注册主类:将@SpringBootApplication标注的主类注册到容器,作为配置类
4. 刷新上下文(refreshContext

这是最核心的步骤,本质是调用 Spring 的AbstractApplicationContext.refresh()方法(Spring 容器初始化的标准流程),同时 SpringBoot 在此基础上扩展了内嵌容器启动的逻辑。

java运行

private void refreshContext(ConfigurableApplicationContext context) {refresh(context); // 调用Spring的refresh()if (this.registerShutdownHook) {try {context.registerShutdownHook(); // 注册关闭钩子} catch (AccessControlException ex) {// 忽略权限异常}}
}
  • Spring 原生refresh()流程(核心步骤):

    • prepareRefresh():准备刷新(验证环境、初始化属性源等)
    • obtainFreshBeanFactory():创建 BeanFactory
    • invokeBeanFactoryPostProcessors():执行 BeanFactory 后置处理器(如解析@Configuration类、处理@ComponentScan扫描 Bean)
    • registerBeanPostProcessors():注册 Bean 后置处理器(用于 Bean 的初始化前后增强)
    • initMessageSource():初始化消息源(国际化)
    • initApplicationEventMulticaster():初始化事件多播器
    • onRefresh()SpringBoot 扩展点(内嵌容器启动在此执行)
    • registerListeners():注册监听器
    • finishBeanFactoryInitialization():实例化所有非懒加载的单例 Bean
    • finishRefresh():完成刷新(发布ContextRefreshedEvent
  • SpringBoot 的onRefresh()扩展:对于 Web 应用(如ServletWebServerApplicationContext),onRefresh()会调用createWebServer()创建内嵌 Web 服务器(Tomcat/Undertow/Jetty):

    java运行

    @Override
    protected void onRefresh() {super.onRefresh();try {createWebServer(); // 创建Web服务器} catch (Throwable ex) {throw new ApplicationContextException("Unable to start web server", ex);}
    }private void createWebServer() {WebServer webServer = this.webServer;ServletContext servletContext = getServletContext();if (webServer == null && servletContext == null) {// 1. 获取Web服务器工厂(如TomcatServletWebServerFactory)ServletWebServerFactory factory = getWebServerFactory();// 2. 创建Web服务器(如Tomcat)this.webServer = factory.getWebServer(getSelfInitializer());} else if (servletContext != null) {try {getSelfInitializer().onStartup(servletContext);} catch (ServletException ex) {throw new ApplicationContextException("Cannot initialize servlet context", ex);}}initPropertySources();
    }
    
5. 执行 Runner(callRunners

启动完成后,会执行所有CommandLineRunnerApplicationRunner接口的实现类,用于在应用启动后执行自定义逻辑(如数据初始化):

java运行

private void callRunners(ApplicationContext context, ApplicationArguments args) {List<Object> runners = new ArrayList<>();runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());AnnotationAwareOrderComparator.sort(runners); // 按@Order排序for (Object runner : new LinkedHashSet<>(runners)) {if (runner instanceof ApplicationRunner) {callRunner((ApplicationRunner) runner, args);} else if (runner instanceof CommandLineRunner) {callRunner((CommandLineRunner) runner, args);}}
}

四、核心原理总结

  1. SPI 机制:通过META-INF/spring.factories加载初始化器、监听器、自动配置类,实现 "插件化" 扩展。
  2. 事件驱动:通过SpringApplicationRunListener在启动各阶段发布事件(如ApplicationStartingEventApplicationReadyEvent),允许监听器介入启动过程。
  3. 自动配置:在refresh()阶段,@EnableAutoConfiguration通过AutoConfigurationImportSelector加载spring.factories中的自动配置类(如DataSourceAutoConfiguration),结合@Conditional条件注解实现按需配置。
  4. 内嵌容器:通过onRefresh()扩展点创建内嵌 Web 服务器(Tomcat 等),无需外部容器部署。

通过以上机制,SpringBoot 实现了 "零配置" 启动,大幅简化了 Spring 应用的开发与部署。

http://www.dtcms.com/a/414088.html

相关文章:

  • 墙绘产品展示交易平台|基于SpringBoot和Vue的墙绘产品展示交易平台(源码+数据库+文档)
  • 开源项目Sherpa-onnx:全平台离线语音识别的轻量级高性能引擎
  • 【大数据技术】ClickHouse配置详细解读
  • 企业网站建设价格表好的电商网站建设与维护意味着什么
  • Spring AI(七)Spring AI 的RAG实现集合火山向量模型+阿里云Tair(企业版)
  • 情绪点设置在开源AI大模型驱动的S2B2C商城小程序AI智能名片中的应用研究
  • 246-基于Django的美食菜谱数据分析推荐系统
  • 阿里云ECS服务器网站配置HTTPS连接
  • 带有渐变光晕
  • 针织厂家东莞网站建设河北教育网站建设
  • MySQL InnoDB压缩:OLTP性能优化实战
  • 【软件架构设计(40)】数据库规范化与性能优化
  • 鸿蒙NEXT蓝牙服务开发概述:构建无缝连接的物联网体验
  • 5G-A无源物联网:深度解析“不插电“智能的底层技术原理
  • Oracle与Kingbase深度兼容体验:从连接配置到性能优化全解析
  • github push 端口不通解决方案
  • OpenLayers地图交互 -- 章节十四:拖拽缩放交互详解
  • C++中 optional variant any 的使用
  • unity3d PuppetMaster 布娃娃插件在学习
  • 复古胶片风格室内人像自拍摄影后期Lr调色教程,手机滤镜PS+Lightroom预设下载!
  • 网站开发之前前后端不分离wordpress 缓存首页
  • 【仿生机器人】基于 GPT-SoVITS 的 发声器
  • 二分查找思路详解,包含二分算法的变种,针对不同题的做法
  • 58同城枣庄网站建设wordpress 会员分值
  • C# .NetCore WebApi 性能改进 响应压缩
  • PyTorch CNN 改进:全局平均池化与 CIFAR10 测试分析
  • 精读C++20设计模式——创造型设计模式:单例模式
  • 网络实践——基于epoll_ET工作、Reactor设计模式的HTTP服务
  • 设计模式-行为型设计模式(针对对象之间的交互)
  • 选手机网站彩票网站开发制作模版