文章目录
前言
在 Spring applicationContext refresh() 方法的逻辑末尾,有一个注册事件发布器
和注册监听器的操作,并且,在refresh()结束之后,发布了一个事件.
Spring 允许当一个事件发生时,引发其他 关注者的事件.
Spring 中的 观察者模式
refresh()方法完成了 多事件处理器的注册、事件监听器的注册.
这是 Spring 对设计模式中观察者模式的实践.
事件发布后,多事件处理器负责将事件通知给所有注册的事件监听器.
Spring 事件相关的类/接口介绍
多事件处理器
事件发布的代码逻辑内部会获取多事件处理器,事件处理器获取所有的 Spring 监听器对象,然后依次调用监听器对象的方法
默认多事件处理器是在 refresh()方法中,初始化 applicationContext 对象的过程中创建的,具体类为
org.springframework.context.event.SimpleApplicationEventMulticaster
Spring 中关键的几个重要事件类
Spring 的 applicationContext 的事件有下面几个
ContextClosedEvent
ContextRefreshedEvent refresh()方法中进行了调用
ContextStartedEvent
ContextStoppedEvent
事件监听器类
需要实现接口 ApplicationListener
覆盖重写 onApplicationEvent 方法
refresh() 方法中实例化并注册所有 实现了java.util.EventListener. ApplicationListener 的 bean
自定义事件发布与监听
Spring 允许我们自定义事件、监听器并且进行事件发布,下面给出例子.
自定义监听器
自定义监听器需要实现接口 ApplicationListener
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class MyListener implements ApplicationListener<ApplicationEvent> {
@Override
public void onApplicationEvent(ApplicationEvent event) {
System.out.println("有监听事件被触发:"+event.getClass());
if(event instanceof ContextRefreshedEvent) {
System.out.println("事件类型: applicationContext 初始化完毕");
}
}
}
自定义事件
需要实现 ApplicationEvent 类
import org.springframework.context.ApplicationEvent;
/**
* 自定义事件
* */
public class MyEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
public MyEvent(Object source) {
super(source);
}
}
自定义事件的发布——即效果查看
自定义
public static void main(String[] args) {
//加载配置文件,获取 applicationContext 对象
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:applicationContext2.xml");
//通过 applicationContext 发布自定义事件
applicationContext.publishEvent(new MyEvent(applicationContext));
}
- xml 文件内容
<bean class="com.bestcxx.test.MyListener"></bean>
- 测试结果
有监听事件被触发:class org.springframework.context.event.ContextRefreshedEvent
有监听事件被触发:class com.bestcxx.test.MyEvent
延伸——ApplicationListener 和 ServletContextListener
二者都是关于监听器的接口,不同之处在于.
ApplicationListener 属于 Spring 事件的监听器类需要实现的接口.
ServletContextListener 属于 Servlet 事件的监听器类需要实现的接口.
从具体应用来说, ServletContextListener 的调用在于 servlet 项目中,比如用于 servlet 项目启动阶段初始化
https://blog.csdn.net/bestcxx/article/details/99402140
ApplicationListener只能用于 Spring 场景的使用.
参考链接
[1]、https://blog.csdn.net/yu_kang/article/details/88389700#EventListener_318
[2]、https://blog.csdn.net/yu_kang/article/details/88727188
[3]、https://blog.csdn.net/tonysong111073/article/details/88385078