在 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 MailSendEvent extends ApplicationContextEvent { private String