Spring ApplicationEvent 使用
ApplicationEvent為Spring的事件基類,可通過@EventListener或實作ApplicationListener接口進行監聽
監聽及觸發事件
自定義事件
import org.springframework.context.ApplicationEvent;
public class CustomAnnotationEvent extends ApplicationEvent {
private static final long serialVersionUID = -4180050946434009635L;
/**
* 類型
*/
private String type;
/**
* 構造方法
*
* @param source 事件源
* @param type 類型
*/
public CustomAnnotationEvent(Object source, String type) {
super(source);
this.type = type;
}
/**
* 擷取類型
*
* @return 擷取類型
*/
public String getType() {
return type;
}
}
抛出事件
//spring注入
@Autowired
private ApplicationContext applicationContext;
...
CustomAnnotationEvent event = new CustomAnnotationEvent(this, "annotation");
applicationContext.publishEvent(event);
監聽事件
@EventListener
public void listenCustomAnnotationEventAll(CustomAnnotationEvent event) {
log.info("listenCustomAnnotationEventAll:{}", JSONUtil.toJsonStr(event));
}
監聽事件及抛出事件的類需為spring管理的bean
其它
@EventListener(condition = "#event.type eq 'anycAnnotation' ")
@Async
public void listenCustomAnnotationAsyncEvent(CustomAnnotationEvent event) {
log.info("listenCustomAnnotationEvent1:{}", JSONUtil.toJsonStr(event));
}
- 異步事件:在方法上增加@Async注解則會将事件處理轉為異步處理,異常及耗時不會影響抛出事件的方法,需在啟動類中增加@EnableAsync開啟此功能
- 條件過濾:@EventListener注解中condition為SpEL表達式,可通路參數中的屬性進行判斷是否處理此事件
- 同時監聽多個事件:可使用@EventListene注解中classes條件擴充監聽的事件
@EventListener(classes = { CustomAnnotationEvent.class, CustomAsyncErrorEvent.class,CustomAsyncEvent.class, CustomMetohEvent.class})
public void handleMultipleEvents(ApplicationEvent event) {
log.info("handleMultipleEvents:{}", JSONUtil.toJsonStr(event));
}
标準事件
事件類 | 說明 |
---|---|
ContextRefreshedEvent | ApplicationContext初始化或重新整理時釋出 |
ContextStartedEvent | 手動調用start()方法時釋出 |
ContextStoppedEvent | 手動調用stop()方法時釋出 |
ContextClosedEvent | ApplicationContext關閉時釋出 |
另還有很多内置事件可通過檢視ApplicationEvent子類來檢視,例如SessionCreationEvent,KafkaEvent,RedisKeyspaceEvent等