将数据加载到内存中
1、建立InitListener.java
package app.util;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.jboss.logging.Logger;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import com.test.ResourceService;
/**
* 加载数据到内存案例
* @author 浅陌
*
*/
public class InitListener extends HttpServlet implements ServletContextListener {
/**
*
*/
private static final long serialVersionUID = 1L;
public static Map<String, Object> contextMap=new HashMap<String,Object>();
private Logger logger = Logger.getLogger(InitListenerMobileResourceTree.class);
public void init() throws ServletException{
// logger.info("====初始化方法运行初完毕====");
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
logger.info("this is last destroyeed ");
}
@Override
public void contextInitialized(ServletContextEvent sce) {//获取要加载的数据方法
try {
/*
*如果在获取数据时用到其他项目包中的接口,可以用如下方法
* WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
* ResourceService resourceService = (ResourceService) wac.getBean("resourceService");// 跑批接口的实现类
* 在springMVC.XML 中加入
* <bean id="resourceService" class="com.test.ResourceService" />
*/
String JsonStr = 获取加载出来的数据(类型视情况而定)
//将数据放到定义好的contextMap中
contextMap.put("JsonStr", JsonStr);
} catch (Exception e) {
e.printStackTrace();
}
logger.info(contextMap);
}
}
2.配置web.xml
<listener>
<listener-class>app.util.InitListener</listener-class>
</listener>
3.获取内存中的数据
InitListener.contextMap.get("JsonStr");