您的位置:首页 > 编程语言 > Java开发

spring项目中监听器的写法

2010-10-22 10:42 357 查看
先说说监听器的作用:在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.
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐