Spring Boot如何在启动时取得servletContext

文章介绍了在SpringBoot应用启动时尝试获取servletContext返回null的问题,原因是servletContext尚未初始化完成。通过添加ApplicationListener和利用spring.factories配置,可以在SpringBoot启动后安全地获取servletContext。作者提供了一个TestListener类示例,该类实现了ApplicationContextAware和ApplicationListener接口,以便在应用启动后执行自定义处理。

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

小结

Sping Boot在启动的时候尝试获取servletContext的时候会返回null空,进行了一些尝试,可以在Spring Boot启动后获取servletContext。

问题

Sping Boot在启动的时候尝试获取servletContext的时候往往会返回null空,是因为servletContext还没有被初始化完成。

以下办法返回null空

SpringBeanContext servletContext = new SpringBeanContext();
servletContext.contextInitialized();
servletContext = servletContext.getServletContext();

以下自动注入Autowire也不行,

@Autowired
private ServletContext servletContext;

以下办法也是不行的,Spring Boot也没有web.xml可以配置。

servletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();

解决

尝试了等待Spring Boot启动后来获取这个ServletContext,是可以的。这里使用了springboot扩展机制 - spring factories

META-INFspring.factories中设置以下触发。

org.springframework.context.ApplicationListener=\
com.bean.TestListener

再通过以下的过程是可以取得ServletContext的:

public class TestListener implements ApplicationContextAware,
        ApplicationListener<ApplicationStartedEvent>
{
    private ApplicationContext ctx;

    @Autowired
    private ServletContext servletContext;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event)
    {
        //get the container who trigger the event
        ConfigurableApplicationContext c = event.getApplicationContext();
        if (c == ctx)
        {
            System.out.println("-----Event trigger container and listener container are the same. -----");
        }
        // add in cusomized process.
        System.out.println("========Execute customized process. =======");
    }

    // interface to inject method, and access to Spring container 
    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException
    {
        this.ctx = ctx;
    }
}

参考

优快云: spring boot 获取applicationContext servletContext
优快云: SpringBoot获取ServletContext和webApplicationConnect几种方法
优快云: spring项目获取ServletContext
springboot2启动时执行,初始化(或定时任务)servletContext问题
优快云: Spring Boot 定义系统启动任务
优快云: springboot扩展机制——spring factories
优快云: spring框架监听ServletContext启动,并加入一些属性到ServletContext
优快云: Spring Boot 定义系统启动任务
优快云: 第二十四节 SpringBoot使用spring.factories
Spring Boot 你不得不会的 spring.factories 配置
springboot2启动时执行,初始化(或定时任务)servletContext问题
springboot自动配置原理以及spring.factories文件的作用详解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值