需求:springboot 启动后自动执行,初始化数据,并将数据放到 servletContext 中。
首先,不可使用 ServletContextListener 即不能用 @WebListener ,因为 servlet 容器初始化后,spring 并未初始化完毕,不能使用 @Autowired 注入 spring 的对象。代码如下:
- 可以实现 ApplicationListener
@Component
public class SettingDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
WebApplicationContext webApplicationContext =
(WebApplicationContext)contextRefreshedEvent.getApplicationContext();
ServletContext servletContext = webApplicationContext.getServletContext();
servletContext.setAttribute("key", "value");
}
}
- 使用注解注入
service 类里注入 servletContext
@Autowired private ServletContext servletContext;
service 类里要启动执行的方法加上注解
@P