目录
(2)ApplicationEventPublisher 发布事件
3、Asynchronous Listeners 异步监听器
1、标准的 Spring 事件机制
ApplicationContext 中的事件处理是通过 ApplicationEvent 类和 ApplicationListener 接口实现的。如果一个 Bean(监听器实例)实现了 ApplicationListener 接口,并被部署到 Spring 容器中,那么每次在容器中发布一个 ApplicationEvent 事件,该 Bean (监听器实例)都会被通知到。本质上,这种机制就是一个观察者的设计模式。// 事件、监听器、观察者模式。
在 Spring 4.2 中,事件的基础结构得到了显著的改进,并且提供了基于注解的模型以及发布任意事件的能力(也就是说,一个对象不一定继承 ApplicationEvent ),当这样的对象被发布时,Spring 为你将这个对象自动包装在一个事件中。// 发布一个不继承 ApplicationEvent 的事件?怎样实现,如果不继承 ApplicationEvent 怎么会知道它是一个事件的实例?
Spring 中提供了一些标准事件(内置事件),了解 Spring 中的内置事件,请点击这里。// 这里简单概述一下,主要有:
- 容器刷新事件(ContextRefreshedEvent)
- 容器启动事件(ContextStartedEvent)
- 容器停止事件(ContextStoppedEvent)
- 容器关闭事件(ContextClosedEvent)
- 请求处理事件(RequestHandledEvent)
- Servlet 请求处理事件(ServletRequestHandledEvent)
(1)ApplicationEvent 自定义事件
在 Spring 中,你可以创建和发布自己的自定义事件。下面的例子展示了一个继承了 Spring ApplicationEvent 类的自定义事件类:
import org.springframework.context.ApplicationEvent;
public class BlockedListEvent extends ApplicationEvent {
private final String address;
private final String content;
public BlockedListEvent(Object source, String address, String content) {
super(source);
this.address = address;
this.content = content;
System.out.println("实例化BlockedListEvent...");
}
// accessor and other methods...
}
(2)ApplicationEventPublisher 发布事件
如果要发布一个自定义的 ApplicationEvent 事件,需要调用 ApplicationEventPublisher 中的 publishEvent() 方法。通常情况下,会去创建一个新的类,然后通过实现 ApplicationEventPublisherAware 接口来获取一个默认的 Publisher,最后把该类注册为容器的一个 Bean。下边的例子展示了这样一个类:// 不直接使用 ApplicationContext 调用 publishEvent() 的原因,看起来有种最少知道原则的意思。
public class EmailService implements ApplicationEventPublisherAware {
private List<String> blockedList;
// 使用事件发布者,与 Spring

最低0.47元/天 解锁文章
1万+

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



