spring ApplicationEvent 和 Listener
ApplicationEvent
ApplicationEvent
以及Listener
是Spring为我们提供的一个事件监听、订阅的实现,内部实现原理是观察者设计模式,设计初衷也是为了系统业务逻辑之间的解耦,提高可扩展性以及可维护性。
通过ApplicationEvent
类和ApplicationListener
接口来提供在ApplicationContext
中处理事件。如果一个 bean 实现ApplicationListener
,那么每次 ApplicationEvent 被发布到ApplicationContext
上,那个 bean 会被通知。
Spring 事件的使用
- 事件的定义
1、
ApplicationEvevnt
:继承 EventObject 类,自定义事件源应该继承该类
2、ApplicationEventListener
:继承EventListener接口,自定义监听者可以通过实现该接口
3、ApplicationEventPublisher
:封装了事件发布的方法,通知所有在 Spring 中注册的监听者进行处理
- 注意 : 基于Spring提供的基类,可以进行自定义各类符合业务和流程的事件;自定义的监听者实现类,可以由 Spring 容器进行管理,只需要通过
ApplicationEventPublisher
进行发布进行,不用自己去实现监听者的注册、通知等等过程。
ApplicationEvent 源码
public abstract class ApplicationEvent extends EventObject {
private static final long serialVersionUID = 7099057708183571937L;
/** 事件发生的时间 **/
private final long timestamp = System.currentTimeMillis();
/** 发布源事件 **/
public ApplicationEvent(Object source) {
super(source);
}
/** 获取事件戳 **/
public final long getTimestamp() {
return this.timestamp;
}
}
ApplicationListener
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
void onApplicationEvent(E var1);
}
- 注意 :通过实现
ApplicationListener
接口来实现一个事件监听者,ApplicationListener接口可以通过泛型事件的传入,来实现对指定事件的监听;通过重写 onApplicationEvent(E event) 方法来实现对事件具体的业务处理
--
ApplicationEventPublisher
@FunctionalInterface
public interface ApplicationEventPublisher {
default void publishEvent(ApplicationEvent event) {
publishEvent((Object) event);
}
void publishEvent(Object event);
}
- Spring 通过 ApplicationEventPublisher 获取 ApplicationContext 进行事件的发布
案例
- 通过继承
ApplicationEvent
实现自定义事件
public class TestApplicationEvent extends ApplicationEvent {
private String msg;
public TestApplicationEvent(Object source , String msg) {
super(source);
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "TestApplicationEvent{" +
"msg='" + msg + '\'' +
'}';
}
}
- 注意 :
TestApplicationEvent
可以添加需要处理的具体实体类的属性进行操作
- 通过继承
ApplicationListener
实现自定义监听器
public class TestApplicationListener implements ApplicationListener<TestApplicationEvent> {
@Override
public void onApplicationEvent(TestApplicationEvent testApplicationEvent) {
System.out.println(testApplicationEvent);
}
}
- 通过
ApplicationContext
进行事事件的发布
ApplicationContext context = SpringUtil.getApplicationContext();
context.publishEvent(new TestApplicationEvent(this , "123"));
- 注意 : 如果一个事件需要被多个监听器进行处理可以使用
@Order
进行监听器执行顺序的之定义,@Order(value = )
value 值越小表示执行优先级越高
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)