业务场景:如果我们项目中有一些常用属性表,可能我们会经常用到。这时候就可以在项目启动时,把数据放到静态map里,在用的时候就不用查数据了,提高程序效率,简化了代码。
实现方案:
1。创建一个ServletContextListener的实现类
package com.travel.util;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.travel.service.FlighCondRecordService;
public class MyListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent sce) {
try {
//项目启动时加载,需配置对应的web.xml
ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
Object bean = context.getBean( "flighCondRecordServiceImpl" );
FlighCondRecordService fs = (FlighCondRecordService)bean;
fs.saveAirMap();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在web.xml中添加listener
<listener>
<listener-class>com.travel.util.MyListener</listener-class>
</listener>
@Override
public void saveAirMap() {
if (CacheAir.cacheAirport.isEmpty()) {
List<FlightCommAttr> findType = flightCommAttrDao.findType("airport");
for (int i = 0; i < findType.size(); i++) {
CacheAir.cacheAirport.put(findType.get(i).getCode(), findType.get(i).getCodeDesc());
}
}
if (CacheAir.cacheAirCompany.isEmpty()) {
List<FlightCommAttr> airCompany = flightCommAttrDao.findType("airCompany");
for (int i = 0; i < airCompany.size(); i++) {
CacheAir.cacheAirCompany.put(airCompany.get(i).getCode(),airCompany.get(i).getCodeDesc());
}
}
if (CacheAir.cacheFlightTime.isEmpty()) {
List<FlightCommAttr> flightTime = flightCommAttrDao.findType("flightTime");
for (int i = 0; i < flightTime.size(); i++) {
CacheAir.cacheFlightTime.put(flightTime.get(i).getCode(),flightTime.get(i).getCodeDesc());
}
}
if (CacheAir.cacheCarbinRank.isEmpty()) {
List<FlightCommAttr> carbinRank = flightCommAttrDao.findType("carbinRank");
for (int i = 0; i < carbinRank.size(); i++) {
CacheAir.cacheCarbinRank.put(carbinRank.get(i).getCode(),carbinRank.get(i).getCodeDesc());
}
}
if (CacheAir.cacheCity.isEmpty()) {
List<FlightCommAttr> city = flightCommAttrDao.findType("cityCN");
for (int i = 0; i < city.size(); i++) {
CacheAir.cacheCity.put(city.get(i).getCode(),city.get(i).getCodeDesc());
}
}
}
public class CacheAir {
public static final Map<String,String> cacheAirport =new LinkedHashMap<String,String>();
public static final Map<String,String> cacheAirCompany=new LinkedHashMap<String,String>();
public static final Map<String,String> cacheFlightTime=new LinkedHashMap<String,String>();
public static final Map<String,String> cacheCarbinRank=new LinkedHashMap<String,String>();
public static final Map<String,String> cacheCity=new LinkedHashMap<String,String>();
}