Spring 實現自定義監聽器案例
在一般的javaWeb項目中經常有一些緩存是需要再項目啟動的時候加載到內存中,這樣就可以使用自定義的監聽器來實現。
1、在web.xml中聲明
<!-- 自定義監聽 啟動加載系統參數 --> <listener> <listener-class>com.cn.framework.constant.OmsConfigLoader</listener-class></listener>
2、創建類OmsConfigLoader 實現接口 ServletContextListener,項目啟動的時候service還沒有注入,此時調用service的方法會報錯,因為在web容器中無論是servlet還是Filter都不是Spring容器來管理的。
listener的生命周期是web容器維護的,bean的生命周期是由Spring容器來維護的,所以在listener中使用@Resource,listener不認識,
可以溝通過如下方法來解決:使用WebApplicationContextUtils工具類,該工具類的作用是獲取到spring容器的引用,進而獲取到我們需要的bean實例。
package com.cn.framework.constant;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import org.apache.log4j.Logger;import org.springframework.web.context.support.WebApplicationContextUtils;import com.kxs.service.systemService.ISystemService;public class OmsConfigLoader implements ServletContextListener {private static Logger LOG = Logger.getLogger(OmsConfigLoader.class);@Overridepublic void contextDestroyed(ServletContextEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void contextInitialized(ServletContextEvent arg0) {LOG.info('==> 加載OMS系統配置信息 Start ==');try {ISystemService iSystemService = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()).getBean(ISystemService.class);iSystemService.refreshCache();} catch (Exception e) {e.printStackTrace();LOG.info(e.toString());}LOG.info('==> 加載OMS系統配置信息 End ==');}}
補充:Spring-xml配置自定義事件監聽器
一、自定義事件Spring中使用自定義事件類型:
第一步:自定義事件類型:自定義類需要繼承Spring中org.springframework.context.ApplicationEvent類
第二步:設置事件監聽器,實現org.springframework.context.ApplicationListener<自定義事件類型>接口,重寫onApplicationEvent方法監聽事件源
第三步:將事件監聽器配置到Spring中,通過xml配置文件將事件監聽器配置到bean容器中
第四步:Spring容器(container容器發布事件)發布事件
自定義事件類型
public class RainEvent extends ApplicationEvent { private static final long serialVersionUID = 1L; public RainEvent(Object source) { super(source); } }
監聽器:可以創建多個監聽器
public class RainEventListener1 implements ApplicationListener<RainEvent> { //監聽rainevent事件,調用當前方法 @Override public void onApplicationEvent(RainEvent event) { Object source = event.getSource(); System.out.println('監聽器1:'+source); }}public class RainEventListener2 implements ApplicationListener<RainEvent> { //監聽rainevent事件,調用當前方法 @Override public void onApplicationEvent(RainEvent event) { Object source = event.getSource(); System.out.println('監聽器2:'+source); }}
xml配置文件將監聽器配置到bean容器中
<!-- 配置監聽器,向spring容器發布事件,自動觸發監聽器的onApplicationEvent方法 --><bean class='com.briup.ioc.event.RainEventListener1'></bean><bean class='com.briup.ioc.event.RainEventListener2'></bean>
bean容器發布事件
public void ioc_event() { try { String path = 'com/briup/ioc/event/event.xml'; ApplicationContext container = new ClassPathXmlApplicationContext(path); container.publishEvent(new RainEvent('打雷了,下雨了!')); } catch (Exception e) { e.printStackTrace(); }}
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章:
