SpringBoot通过main方法启动web项目实践

SpringBoot通过SpringApplication.run()启动Web项目,自动推断应用类型,加载初始化器与监听器,配置SpringMVC组件,启动嵌入式服务器,实现零配置启动

目录
  • 1. 启动入口:SpringApplication.run()
  • 2. SpringApplication初始化
  • 3. run()方法核心流程
  • 4. 嵌入式 Web 服务器启动关键点
    • 4.1refreshContext()方法触发服务器启动
    • 4.2ServletWebServerApplicationContext的核心作用
    • 4.3ServletWebServerFactory实例化服务器
  • 5. Spring MVC 组件自动配置
    • 6. 最终启动结果
      • 总结:启动流程关键点

        Spring Boot 通过 main 方法启动 Web 项目的过程涉及多个核心组件和自动化机制,下面从源码角度详细拆解:

        1. 启动入口:SpringApplication.run()

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

        SpringApplication.run() 是启动的核心入口,它主要完成以下工作:

        2. SpringApplication初始化

        // SpringApplication 构造函数核心逻辑
        public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
            // 1. 设置资源加载器
            this.resourceLoader = resourceLoader;
            // 2. 校验并保存主配置类(即 @SpringBootApplication 标注的类)
            this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
            // 3. 推断应用类型(REACTIVE、SERVLET、NONE)
            this.webApplicationType = WebApplicationType.deduceFromClasspath();
            // 4. 加载并实例化 ApplicationContextInitializer
            setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
            // 5. 加载并实例化 ApplicationListener
            setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
            // 6. 推断 main 方法所在类
            this.mainApplicationClass = deduceMainApplicationClass();
        }
        

        关键步骤:

        • 应用类型推断:通过检查类路径中是否存在 org.springframework.web.reactive.DispatcherHandler(REACTIVE)或 javax.servlet.Servlet(SERVLET)来确定应用类型。
        • 初始化器(Initializer):从 META-INF/spring.factories 加载 ApplicationContextInitializer,用于在 ApplicationContext 刷新前自定义配置。
        • 监听器(Listener):加载 ApplicationListener,监听启动过程中的事件(如 ApplicationStartingEvent)。

        3. run()方法核心流程

        public ConfigurableApplicationContext run(String... args) {
            // 1. 计时和发布启动事件
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            ConfigurableApplicationContext context = null;
            Collection exceptionReporters = new ArrayList();
            configureHeadlessProperty();
            
            // 2. 获取并启动监听器
            SpringApplicationRunListeners listeners = getRunListeners(args);
            listeners.starting();
            
            try {
                // 3. 构建应用参数和环境配置
                ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
                ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
                
                // 4. 创建并配置 ApplicationContext
                context = createApplicationContext();
                exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                        new Class[] { ConfigurableApplicationContext.class }, context);
                
                // 5. 准备上下文(加载 Bean 定义)
                prepareContext(context, environment, listeners, applicationArguments, printedBanner);
                // 6. 刷新上下文(核心启动逻辑)
                refreshContext(context);
                // 7. 刷新后的回调处理
                afterRefresh(context, applicationArguments);
                // 8. 发布应用就绪事件
                listeners.started(context);
                // 9. 执行 Runner(如 CommandLineRunner)
                callRunners(context, applicationArguments);
            }
            catch (Throwable ex) {
                handleRunFailure(context, ex, exceptionReporters, listeners);
                throw new IllegalStateException(ex);
            }
            
            stopWatch.stop();
            if (this.logStartupInfo) {
                new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
            }
            // 10. 发布应用运行中事件
            listeners.running(context);
            return context;
        }
        

        4. 嵌入式 Web 服务器启动关键点

        4.1refreshContext()方法触发服务器启动

        private void refreshContext(ConfigurableApplicationContext context) {
            refresh(context);
            if (this.registerShutdownHook) {
                try {
                    context.registerShutdownHook();
                }
                catch (AccessControlException ex) {
                    // Not allowed in some environments.
                }
            }
        }
        
        protected void refresh(ConfigurableApplicationContext context) {
            // 调用 AbstractApplicationContext 的 refresh() 方法
            context.refresh();
        }
        

        4.2ServletWebServerApplicationContext的核心作用

        对于 Web 应用,ApplicationContext 实际类型为 AnnotationConfigServletWebServerApplicationContext,它继承自 ServletWebServerApplicationContext,后者在 refresh() 过程中会:

        // ServletWebServerApplicationContext 核心方法
        @Override
        protected void onRefresh() {
            super.onRefresh();
            try {
                // 创建并启动嵌入式 Web 服务器
                createWebServer();
            }
            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. 获取 ServletWebServerFactory(如 TomcatServletWebServerFactory)
                ServletWebServerFactory factory = getWebServerFactory();
                // 2. 创建并配置 Web 服务器
                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();
        }
        

        4.3ServletWebServerFactory实例化服务器

        以 Tomcat 为例,TomcatServletWebServerFactorygetWebServer() 方法会:

        @Override
        public WebServer getWebServer(ServletContextInitializer... initializers) {
            // 1. 创建 Tomcat 实例
            Tomcat tomcat = new Tomcat();
            // 2. 配置服务器基本参数(端口、上下文路径等)
            File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
            tomcat.setBaseDir(baseDir.getAbsolutePath());
            Connector connector = new Connector(this.protocol);
            tomcat.getService().addConnector(connector);
            customizeConnector(connector);
            tomcat.setConnector(connector);
            tomcat.getHost().setAutoDeploy(false);
            // 3. 配置 ServletContextInitializer(如 DispatcherServlet)
            prepareContext(tomcat.getHost(), initializers);
            // 4. 启动服务器
            return getTomcatWebServer(tomcat);
        }
        

        5. Spring MVC 组件自动配置

        通过 WebMvcAutoConfiguration 自动配置核心组件:

        • DispatcherServlet:作为前端控制器,处理所有 HTTP 请求。
        • HandlerMapping:映射 URL 到具体的 Controller 方法。
        • ViewResolver:解析视图名称到实际视图。

        关键代码(WebMvcAutoConfiguration):

        @Bean
        @Primary
        @ConditionalOnMissingBean(DispatcherServlet.class)
        public DispatcherServlet dispatcherServlet(WebMvcProperties properties) {
            DispatcherServlet dispatcherServlet = new DispatcherServlet();
            dispatcherServlet.setDispatchOptionsRequest(properties.isDispatchOptionsRequest());
            dispatcherServlet.setDispatchTraceRequest(properties.isDispatchTraceRequest());
            dispatcherServlet.setThrowExceptionIfNoHandlerFound(properties.isThrowExceptionIfNoHandlerFound());
            dispatcherServlet.setPublishEvents(properties.isPublishRequestHandledEvents());
            dispatcherServlet.setEnableLoggingRequestDetails(properties.isLogRequestDetails());
            return dispatcherServlet;
        }
        

        6. 最终启动结果

        • 嵌入式服务器(如 Tomcat)启动并监听指定端口(默认 8080)。
        • DispatcherServlet 注册到 Servlet 容器,作为所有请求的入口。
        • Spring 上下文初始化完成,所有 Bean 已加载并可用。
        • ApplicationReadyEvent 发布,标志应用可处理外部请求。

        总结:启动流程关键点

        1. SpringApplication 初始化:推断应用类型、加载初始化器和监听器。
        2. 环境配置:加载 application.properties 等配置源。
        3. ApplicationContext 创建:根据 Web 类型选择相应的上下文实现。
        4. 自动配置:基于依赖和条件注解,自动配置 Web 组件(如 DispatcherServlet)。
        5. 嵌入式服务器启动:通过 ServletWebServerFactory 创建并启动 Tomcat/Jetty。
        6. Spring MVC 初始化:配置请求映射、视图解析等核心组件。

        通过这种机制,Spring Boot 实现了“零配置”启动 Web 项目的能力,开发者只需关注业务逻辑,无需手动处理服务器配置和组件装配。

        以上为个人经验,希望能给大家一个参考,也希望大家多多支持骃骐网。

        您可能感兴趣的文章:

        • SpringBoot main方法结束程序不停止的原因分析及解决方法
        • Springboot解决no main manifest attribute错误
        • SpringBoot在启动类main方法中调用service层方法报“空指针异常“的解决办法
        • springboot项目启动的时候,运行main方法报错NoClassDefFoundError问题
        • springboot项目test文件夹下带main方法的类不能运行问题
        • SpringBoot启动异常Exception in thread “main“ java.lang.UnsupportedClassVersionError
        • Springboot使用maven打包指定mainClass问题

        相关推荐:

        Python类方法定义中必须显式声明self参数

        Python类中定义的方法默认会自动接收实例对象作为第一个参数,若方法签名未包含self,调用时就会报“多传入1个位置参数”的错误——本质是Python隐式传入了实例,而函数未声明接收。 python类方法定义中必须显式声明`self`参数 在Python中,**所有实例方法(即定义在类内部、用于操作实例数据的方法)都必须将`self`作为第一个形参**。这不是约定俗成,而是语言强制要求:当通过实...

        计算每个IP的平均响应时间(Ping均值)的Python实现方法

        本文介绍如何从ping测试结果中提取各ip的延迟数据,并准确计算每个ip对应的平均响应时间,涵盖数据清洗、类型转换、空值处理及完整可运行示例。 本文介绍如何从ping测试结果中提取各ip的延迟数据,并准确计算每个ip对应的平均响应时间,涵盖数据清洗、类型转换、空值处理及完整可运行示例。 在实际网络监控或运维脚本中,常需对多个目标IP执行批量Ping操作,并统计每个IP的平均响应时间(即time=后...

        如何检测Python类是否定义了某个方法_使用hasattr判断callable

        hasattr仅能判断属性是否存在,无法区分方法与普通属性;可靠检测可调用方法需三步:hasattr检查存在性、getattr获取值、callable核验可调用性。 hasattr 能判断方法是否存在,但不能区分方法和普通属性 直接用 hasattr(obj, "method_name") 只能告诉你这个名称在对象或其类上“有”,但它可能是方法、属性、property、甚至只是个数据成员。比如类里...

        为什么Python中的双下划线方法被称为魔法方法_了解其对内置运算符的重载

        魔法方法是Python中以双下划线开头和结尾的特殊方法,由解释器在特定语法(如+、len()、==)触发时自动调用,用于定义类的对象行为协议,实现运算符重载、字符串表示、比较逻辑等功能。 Python 中的双下划线方法(如 __add__、__eq__、__len__)不是“魔法”,而是明确的协议接口——它们被解释器在特定语法触发时自动调用,本质上是 Python 对象模型的契约式约定。 为什么叫...

        Python 中的函数与方法:为什么字符串操作是方法而非独立函数

        Python 将字符串操作(如 lower()、upper())设计为实例方法而非独立函数,核心原因在于面向对象的设计原则——通过封装将行为与数据绑定,提升可读性、可维护性与语义清晰度;同时,这与 Python 的类型系统、命名空间管理及内置类型实现机制深度契合。 python 将字符串操作(如 `lower()`、`upper()`)设计为实例方法而非独立函数,核心原因在于面向对象的设计原则——...

        Python 中函数与方法的设计哲学:为何 lower() 是方法而非函数

        本文解析 Python 中字符串操作为何设计为方法(如 s.lower())而非独立函数(如 lower(s)),从面向对象封装、语义清晰性、命名空间管理及语言一致性角度阐明其设计合理性。 本文解析 python 中字符串操作为何设计为方法(如 `s.lower()`)而非独立函数(如 `lower(s)`),从面向对象封装、语义清晰性、命名空间管理及语言一致性角度阐明其设计合理性。 在 Pyth...

        为什么Django的ORM不触发save方法_分析Python批量更新的局限性

        update() 不触发 post_save 信号,因其绕过 ORM 实例层直接执行 SQL,不调用 save()、不实例化对象;save() 则触发信号、处理 auto_now 等逻辑,但并发下易覆盖字段,需用 update_fields 避免。 update() 方法根本不会调用模型的 save(),这是设计使然,不是 bug。它绕过 ORM 的实例层,直接拼 SQL 执行 —— 所以信号、a...

        如何在Python中获取当前的毫秒级时间戳_使用time.time_ns方法

        time.time_ns() 返回自 Unix 纪元起的纳秒整数,转毫秒需用 // 1_000_000 截断;它比 time.time() 更精确、无浮点误差,适用于高精度时间戳场景。 time.time_ns() 返回的是纳秒,不是毫秒 直接调用 time.time_ns() 得到的是自 Unix 纪元以来的纳秒数(int 类型),不是毫秒。如果你要毫秒级时间戳(即精确到毫秒的整数,常用于日志、...

        如何在Python中将索引转换为普通列_使用reset_index方法

        reset_index()默认将原索引转为列并生成新RangeIndex,列名为原索引名(默认'index');drop=True才丢弃索引不新增列;inplace=True不推荐,应显式赋值;多级索引会生成元组列名,需flatten处理。 reset_index 会把索引变成列,但默认不删掉原索引 调用 reset_index() 最直接的效果是:把当前的行索引(无论是 RangeIndex 还...

        Python类中正确实现列表随机打乱的实践指南

        在Python类初始化时直接对传入列表调用random.shuffle()会导致多个实例共享同一份被修改的数据,根本原因是未创建独立副本;解决方法是使用.copy()或list()构造新列表后再打乱。 在python类初始化时直接对传入列表调用`random.shuffle()`会导致多个实例共享同一份被修改的数据,根本原因是未创建独立副本;解决方法是使用`.copy()`或`list()`构造新...