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