為避免前台顯示權限菜單是每次都從數據庫中讀取,使用ServletContextListener在服務器啟動和關閉時創建和關閉緩存。
在web.xml配置監聽器:
<!-- 配置用於初始化數據的監聽器,一定要配置在spring的ContextLoaderListener之后 --> <listener> <listener-class>com.itcast.oa.util.InitListener</listener-class> </listener>
監聽器類:
@Component public class InitListener implements ServletContextListener{ @Resource private PrivilegeService privilegeService; @Override public void contextInitialized(ServletContextEvent sce) { List<Privilege> topPrivilegeList = privilegeService.findTopList(); sce.getServletContext().setAttribute("topPrivilegeList", topPrivilegeList); System.out.println("=====已准備數據======"); }
實際上,Tomcat不能檢測到Spring容器,而是通過反射生成監聽器實例,而將監聽器類注入到Spring中,Spring容器里面也存在一個監聽器實例,Tomcat自己創建的實例根本用不了Spring注入的內容,所以不能采用注入的方式。
下面是修改:
public class InitListener implements ServletContextListener{ @Override public void contextInitialized(ServletContextEvent sce) { //獲取容器和相關的Service ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()); PrivilegeService privilegeService = (PrivilegeService)ac.getBean("privilegeServiceImpl"); List<Privilege> topPrivilegeList = privilegeService.findTopList(); sce.getServletContext().setAttribute("topPrivilegeList", topPrivilegeList); System.out.println("=====已准備數據======"); }