您的位置:首页 > 其它

在项目启动时 使用监听器加载所有字典表数据

2016-07-07 11:20 316 查看
1.首先在web.xml配置

<listener>
<listener-class>DataDictionaryListener</listener-class>
</listener>


2.书写DataDictionaryListener类

public class DataDictionaryListener extends ContextLoader implements ServletContextListener{

private ArrayList<String> codeArrayList = new ArrayList<String>();//数据字典Code列表

@Override
public void contextInitialized(ServletContextEvent sce) {
//Spring上下文获取及Bean获取
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
DataDictionaryService dataDictionaryService = (DataDictionaryService) applicationContext.getBean("dataDictionaryService");
ServletContext servletContext = sce.getServletContext();

//查询获取数据库所有数据字典Code列表
try {
codeArrayList = dataDictionaryService.getDataDictionaryCodeList();
}catch (Exception e){
System.out.println("============项目启动获取数据字典Code列表出错==================");
e.printStackTrace();
}

//循环CodeList初始化数据字典数据之内存中
try {
for (String code : codeArrayList) {
servletContext.setAttribute(code, dataDictionaryService.getDataDictionaryByStr(code));
}
}catch (Exception ex){
System.out.println("============项目启动存储数据字典列表至内存出错==================");
ex.printStackTrace();
}
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
closeWebApplicationContext(sce.getServletContext());
}
}


 3.从内存中取出每个code对应的list集合dataDictionaryService方法

WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContext servletContext = webApplicationContext.getServletContext();
arrayList = (ArrayList<DataDictionary>) servletContext.getAttribute(code);


  获取到该code对应的arrayList数据。

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: