import java.util.List; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import cn.itcast.oa.domain.Privilege; import cn.itcast.oa.service.PrivilegeService; public class InitListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { // 获取容器与相关的Service对象 ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()); PrivilegeService privilegeService = (PrivilegeService) ac.getBean("privilegeServiceImpl"); // 准备数据:topPrivilegeList List<Privilege> topPrivilegeList = privilegeService.findTopList(); System.out.println("size"+topPrivilegeList.size()); sce.getServletContext().setAttribute("topPrivilegeList", topPrivilegeList); System.out.println("------------> 已准备数据 <------------"); } public void contextDestroyed(ServletContextEvent arg0) { } }
不会变化的数据:
将从数据库查到的信息缓存起来,只访问一次数据库,以后要用直接从内存拿来用:#application.topPrivilegeList
<!-- 用于做初始化工作的监听器,一定要配置到Spring的ContextLoaderListener之后,
因为要用到Spring的容器对象 -->
<listener>
<listener-class>cn.itcast.oa.util.InitListener</listener-class>
</listener>