zoukankan      html  css  js  c++  java
  • 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("=====已准备数据======");
        }
  • 相关阅读:
    iOS优化篇之App启动时间优化
    我是如何从一个小哈喽进阶为高级iOS的?
    windows创建bat文件进行截图
    利用certbot-auto生成证书
    修改Linux的环境变量
    常用的Linux命令(好记性不如烂笔头)
    常用的服务端配置文件(Tomcat、MySQL)
    【极致丝滑】利用postcss-px2vw-pv彻底摆脱编辑器插件,灵活可控地转换px至vw
    np.mgrid函数
    快速了解匈牙利算法
  • 原文地址:https://www.cnblogs.com/zywu/p/5577878.html
Copyright © 2011-2022 走看看