1.实现ServletContext 监听器。在容器启动的时候,用来初始化数据。java
2.实现代码:web
package com.jeeplus.common.utils;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.modules.sys.entity.DictType;
import com.jeeplus.modules.sys.entity.DictValue;
import com.jeeplus.modules.sys.mapper.DictTypeMapper;
import com.jeeplus.modules.sys.utils.DictUtils;
public class ServletContextInitListener implements ServletContextListener {
@Autowired
private DictTypeMapper dictTypeMapper;
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("----------------------------servletContenxt init -------------------------------------");
//每次容器启动的时候,随机生成资源版本号
double version = Math.random();
ServletContext sc = sce.getServletContext();
sc.setAttribute("resourceVersion", version);
// 经过设置这句话,能够 使用注解来获取 Spring容器中的bean
WebApplicationContextUtils.getWebApplicationContext(sc).getAutowireCapableBeanFactory().autowireBean(this);
//接下来初始化 字典缓存
Map<String, List<DictValue>> dictMap = (Map<String, List<DictValue>>)CacheUtils.get(DictUtils.CACHE_DICT_MAP);
if (dictMap==null){
dictMap = Maps.newHashMap();
for (DictType dictType : dictTypeMapper.findList(new DictType())){
List<DictValue> dictList = dictMap.get(dictType.getType());
dictType = dictTypeMapper.get(dictType.getId());
if (dictList != null){
dictList.addAll(dictType.getDictValueList());
}else{
dictMap.put(dictType.getType(), Lists.newArrayList(dictType.getDictValueList()));
}
}
CacheUtils.put(DictUtils.CACHE_DICT_MAP, dictMap);
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("----------------------------servletContenxt destory -------------------------------------");
}
}
复制代码
注意: 经过设置这句话,能够 使用注解来获取 Spring容器中的bean WebApplicationContextUtils.getWebApplicationContext(sc).getAutowireCapableBeanFactory().autowireBean(this);spring
2.web.xml配置监听。缓存
<listener>
<listener-class>com.jeeplus.common.utils.ServletContextInitListener</listener-class>
</listener>
复制代码