in Spring

Spring Boot如何在启动时取得servletContext

小结

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;
    }
}

参考

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

Write a Comment

Comment