在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);
@Resource
private AuthTokenService authTokenService;
private static boolean flag = false; //防止二次調用
@Override
public 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方法被執行兩次。
解決方法:如代碼所示,用個標志標記是否已執行
