Tomcat服務器自動加載監聽器


  為避免前台顯示權限菜單是每次都從數據庫中讀取,使用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("=====已准備數據======");
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM