Spring Boot 2關于ApplicationEvent的使用
- 自定義線程池處理
- 通過@EventListener處理
- 實作ApplicationListener接口自定義監聽
- 實作SmartApplicationListener接口自定義監聽
ApplicationEvent與Listener是Spring提供的一個事件監聽、訂閱的實作,内部實作原理是觀察者設計模式,設計初衷也是解耦。
自定義線程池處理
public String test1() {
taskExecutorConfig.getAsyncExecutor().execute(() -> {
//
});
return "test1";
}
将非主幹邏輯放到背景線程處理,不影響主線程的業務執行時間
通過@EventListener處理
@Component
public class AnnotationRegisterListener {
@EventListener
public void test2(Test1ApplicationEvent event) {
//
}
@EventListener
public void test2(Test2ApplicationEvent event) {
//
}
}
applicationContext().publishEvent(new Test2ApplicationEvent(this, "test2"));
通過注解方式實作對不同event的監聽,不用自定義監聽類
實作ApplicationListener接口自定義監聽
@Component
public class Test3ApplicationListener implements ApplicationListener<Test3ApplicationEvent> {
@Override
public void onApplicationEvent(Test3ApplicationEvent event) {
//
}
}
applicationContext().publishEvent(new Test3ApplicationEvent(this, "test3"));
通過自定義監聽類實作對不同event的監聽
實作SmartApplicationListener接口自定義監聽
@Component
public class Test4SmartApplicationListener implements SmartApplicationListener {
@Override
public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
return eventType == Test4ApplicationEvent.class;
}
@Override
public boolean supportsSourceType(Class<?> sourceType) {
return sourceType == TestServiceImpl.class;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
Test4ApplicationEvent test4ApplicationEvent = (Test4ApplicationEvent) event;
}
@Override
public int getOrder() {
return 1;
}
}
applicationContext().publishEvent(new Test4ApplicationEvent(this, "test4"));
SmartApplicationListener接口繼承了全局監聽ApplicationListener,監聽所有事件釋出。這裡需要指定event類型以及source類型,才能精确監聽到自己想要的
源碼位置:
https://gitee.com/ceclar123/spring-boot-demo/tree/master/ch09