应用场景:
在一般的javaWeb项目中经常有一些缓存是需要再项目启动的时候加载到内存中,这样就可以使用自定义的监听器来实现。
1、在web.xml中声明
com.cn.framework.constant.OmsConfigLoader
2、创建类OmsConfigLoader 实现接口 ServletContextListener,项目启动的时候service还没有注入,此时调用service的方法会报错,因为在web容器中无论是servlet还是Filter都不是Spring容器来管理的。
listener的生命周期是web容器维护的,bean的生命周期是由Spring容器来维护的,所以在listener中使用@Resource,listener不认识,
可以沟通过如下方法来解决:
使用WebApplicationContextUtils工具类,该工具类的作用是获取到spring容器的引用,进而获取到我们需要的bean实例。
package com.cn.framework.constant;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.kxs.service.systemService.ISystemService;
public class OmsConfigLoader implements ServletContextListene