在 JDK 中已经提供相应的自定义事件发布功能的基础类:
java.util.EventObject类 :自定义 事件 类型java.util.EventListener接口:事件的 监听器
首先了解几个概念:

Spring 事件类结构

1. 事件类
事件类也就是定义发送的内容,比如可以通过继承 ApplicationContextEvent 来自定义一个特定事件类。

1.1 ApplicationEvent 类
首先是继承 EventObject 的 ApplicationEvent ,通过source来指定事件源:
public abstract class ApplicationEvent extends EventObject {
/**
* Constructs a prototypical Event.
*
* @param source The object on which the Event initially occurred.
* @throws IllegalArgumentException if source is null.
*/
public ApplicationEvent(Object source) {
super(source);
}
}
1.2 ApplicationContextEvent 类
是主要的容器事件,它有容器启动、刷新、停止以及关闭各种事件的子类。
public class ApplicationContextEvent extends ApplicationEvent {
/**
* Constructs a prototypical Event.
*
* @param source The object on which the Event initially occurred.
* @throws IllegalArgumentException if source is null.
*/
public ApplicationContextEvent(Object source) {
super(source);
}
/**
* Get the <code>ApplicationContext</code> that the event was raised for.
*/
public final ApplicationContext getApplicationContext() {
return (ApplicationContext) getSource();
}
}
public class ContextClosedEvent extends ApplicationContextEvent{
/**
* Constructs a prototypical Event.
*
* @param source The object on which the Event initially occurred.
* @throws IllegalArgumentException if source is null.
*/
public ContextClosedEvent(Object source) {
super(source);
}
}
public class ContextRefreshedEvent extends ApplicationContextEvent{
/**
* Constructs a prototypical Event.
*
* @param source The object on which the Event initially occurred.
* @throws IllegalArgumentException if source is null.
*/
public ContextRefreshedEvent(Object source) {
super(source);
}
}
我们可以通过继承该类来实现,特定的事件类型需求,比如要实现一个邮件发送事件。只需要继承 ApplicationContextEvent 即可:
public class MailSe

本文深入探讨了Spring事件的原理,包括事件类结构,如ApplicationEvent及其子类,EventListener接口和ApplicationListener接口。事件广播器和事件发布者的工作机制也进行了阐述。此外,通过邮件发送事件的实例,展示了Spring事件在实际应用中的使用方法,包括监听器的配置和事件的发布。
最低0.47元/天 解锁文章
5万+

被折叠的 条评论
为什么被折叠?



