• spring项目中监听器的写法


    先说说监听器的作用:在spring项目的有一个大家熟知的监听器:ContextLoaderListener. 该监听器的作用是在web容器自动运行,加载spring的相关的配置文件,完成类的初始化工作。

    在项目中我们因为某些操作会频繁的使用某些查询语句,但是查询数据量大,非常的耗时,每一个操作都会造成用户的等待时间变长,造成很不不好的体验。解决的一种方法就是写一个监听器,在web容器启动时,让它去查询出数据,并把数据放到缓存中。这样用户每一次操作都会自动从缓存中取出数据。

    具体写法:参考ContextLoaderListener,可以看到它继承的是ServletContextListener接口,并实现了contextInitialized(ServletContextEvent sce)和contextDestroyed(ServletContextEvent sce)方法 ,从方法的名称中我们大概就可以猜出这两个方法的大概作用。

    下面看具体的代码:

    代码
    public class CategoryListener implements ServletContextListener {  
           
    private final static Log log = LogFactory.getLog(CategoryListener.class);  
       
    public static final String LOCAL_CATEGORY_MANAGER_BEAN_NAME="localCategoryManager";  
      
       
    public void contextInitialized(ServletContextEvent servletContextEvent) {  
            ServletContext servletContext
    = servletContextEvent.getServletContext();  
      
           
    try {  
                WebApplicationContext wac
    = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);  
                IHello hello
    = (IHello )wac.getBean(“hello”);  
                hello.query();
    //查询数据  
            } catch (Exception e) {  
                log.error(e);  
            }  
        }  
      
       
    public void contextDestroyed(ServletContextEvent servletContextEvent) {  
           
    //To change body of implemented methods use File | Settings | File Templates.  
        }  
    }  
  • 相关阅读:
    牛客网·剑指offer 从尾到头打印链表(JAVA)
    牛客网·剑指offer 替换空格(JAVA)
    简单的用户登录后台程序编写
    牛客网&剑指offer 二维数组中的查找(JAVA)
    洛谷 P1603 斯诺登的密码(JAVA)
    【回溯法】八皇后问题(递归和非递归)
    如何使用SecureCRT让Vim有颜色?
    js 转base64字符串为文件
    springboot 测试类
    oracle 登录、重启服务
  • 原文地址:https://www.cnblogs.com/jifeng/p/1858085.html
Copyright © 2020-2023  润新知