外置tomcat 启动Spring 源码分析详解

本文详细介绍了Tomcat的启动流程,重点关注了SpringServletContainerInitializer在启动过程中的作用。通过分析SpringBootServletInitializer的onStartUp方法,揭示了如何创建和配置Spring上下文。同时,示例代码展示了如何通过SpringApplication.run方法支持本地main方法启动Spring Boot应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tomcat 启动流程见: tomcat 源码分析_caicongyang的博客-CSDN博客

1. 核心类

org.springframework.web.SpringServletContainerInitializer 是通过spring-web 包中SPI 加载javax.servlet.ServletContainerInitializer的实现;

 

本例的 Application通过继承SpringBootServletInitializer来提供tomcat 的调用onStartUp方法

同时也写了一个 SpringApplication.run(Application.class); 来支持 本地main 方法启动;

public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}

2. SpringBootServletInitializer 中的onStartUp 方法

  public void onStartup(ServletContext servletContext) throws ServletException {
        this.logger = LogFactory.getLog(this.getClass());
    //创建spring 上下文
        WebApplicationContext rootAppContext = this.createRootApplicationContext(servletContext);
        if (rootAppContext != null) {
            servletContext.addListener(new ContextLoaderListener(rootAppContext) {
                public void contextInitialized(ServletContextEvent event) {
                }
            });
        } else {
            this.logger.debug("No ContextLoaderListener registered, as createRootApplicationContext() did not return an application context");
        }

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值