第一步:
在web.xml文件中配置spring的servletcontext监听文件以及自己写的servletcontext监听文件,自己写的servletcontext监听文件应放在spring文件之后,需要从spring容器内取对象。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener >
<listener-class>com.bytedance.crm.web.listener.ServletContext</listener-class>
</listener>
第二步:在自己写的servletcontext监听类中继承ServletContextListener接口,重写其方法。注意,不能采用注解的形式注入DAO,会导致空指针异常,必须采用手动方式获取Bean。
public class ServletContext implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
String config = "applicationContext.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(config);
DicTypeDao dicTypeDao = (DicTypeDao) context.getBean("dicTypeDao");
DicValueDao dicValueDao = (DicValueDao) context.getBean("dicValueDao");
List<DicType> list = dicTypeDao.selectAll();
javax.servlet.ServletContext servletContext = servletContextEvent.getServletContext();
for(DicType dicType: list){
String code = dicType.getCode();
List<DicValue> value= dicValueDao.selectValue(code);
servletContext.setAttribute(code,value);
}
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}