Spring 實現自定義監聽器案例
阿新 • • 發佈:2021-01-21
應用場景:
在一般的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); @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } @Override public 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(); } }
以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。