日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

利用Spring的ApplicationEvent执行自定义方法

發布時間:2025/7/25 58 豆豆
生活随笔 收集整理的這篇文章主要介紹了 利用Spring的ApplicationEvent执行自定义方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在Spring中已經定義了五個標準事件,分別介紹如下:
1)ContextRefreshedEvent:當ApplicationContext初始化或者刷新時觸發該事件。
2)ContextClosedEvent:當ApplicationContext被關閉時觸發該事件。容器被關閉時,其管理的所有單例Bean都被銷毀
3) RequestHandleEvent:在Web應用中,當一個http請求(request)結束觸發該事件
4)ContestStartedEvent:Spring2.5新增的事件,當容器調用ConfigurableApplicationContext的Start()方法開始/重新開始容器時觸發該事件
5)ContestStopedEvent:Spring2.5新增的事件,當容器調用ConfigurableApplicationContext的Stop()方法停止容器時觸發該事件
至于之后是否新增的暫時沒研究

業務需求:項目啟動時向數據庫或者Redis初始化微信的access_token
新建SysInition(自定義名字)類,實現ApplicationListener接口,并監控ContextRefreshedEvent事件,在onApplicationEvent()方法中添加事件處理代碼

import javax.annotation.Resource;import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component;import com.phil.hi.service.auth.AuthTokenService;/*** 項目初始化操作類* * @author phil* @date 2017年7月9日**/ public class SysInition implements ApplicationListener<ContextRefreshedEvent> {private static final Logger logger = Logger.getLogger(SysInition.class);@Resourceprivate AuthTokenService authTokenService;private static boolean flag = false; //防止二次調用@Overridepublic void onApplicationEvent(ContextRefreshedEvent event) {if (!flag) {flag= true;String token = authTokenService.findToken();if (StringUtils.isBlank(token)) {logger.info("token is null in db");authTokenService.saveToken();}}} }

spring配置文件:

<bean id="sysInition" class="com.phil.hi.config.SysInition"></bean>

注解定義

在類前加上@Component或@Controller,然后在<context:component-scan base-package="">里加上你的類所在的包名

解決onApplicationEvent(方法被執行兩次以上的問題

原因:無論是使用spring還是spring mvc,系統會存在兩個容器,一個是root application context ,另一個就是projectName-servletContext(作為root application context的子容器)。這種情況下,就會造成onApplicationEvent方法被執行兩次。
解決方法:如代碼所示,用個標志標記是否已執行

轉載于:https://www.cnblogs.com/phil_jing/p/7141513.html

總結

以上是生活随笔為你收集整理的利用Spring的ApplicationEvent执行自定义方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。