springboot 启动执行初始化 servletContext

需求:springboot 启动后自动执行,初始化数据,并将数据放到 servletContext 中。

首先,不可使用 ServletContextListener 即不能用 @WebListener ,因为 servlet 容器初始化后,spring 并未初始化完毕,不能使用 @Autowired 注入 spring 的对象。

推荐使用 ApplicationListener:启动项目, spring 加载完毕后,才执行该 ApplicationListener,并且该 Listener 中可以使用 spring 的内容。

@Component
public class SettingDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        // 将 ApplicationContext 转化为 WebApplicationContext 
        WebApplicationContext webApplicationContext = 
            (WebApplicationContext)contextRefreshedEvent.getApplicationContext();
        // 从 webApplicationContext 中获取  servletContext 
        ServletContext servletContext = webApplicationContext.getServletContext();
        // servletContext设置值
        servletContext.setAttribute("key", "value");
    }
}

参考:http://www.fengyunxiao.cn

猜你喜欢

转载自blog.csdn.net/m0_37202351/article/details/86180998