Spring提供了很方便的事件的处理机制,包括事件类ApplicationEvent和事件监听类ApplicationListener。 他实现的是设计者模式,如果实现了ApplicationListener接口的bean部署到Spring容器中,则每次ApplicationEvent发布到ApplicationContext时,都会通知该bean。

从Spring4.2开始,提供了基于注解的事件,即事件对象不一定要从ApplicationEvent来扩展。Spring会自动将其封装成一个事件对象。

下面是Spring的标准事件描述:

Event 解释
ContextRefreshedEvent 在初始化或刷新ApplicationContext时发布(例如,通过在ConfigurableApplicationContext接口上使用refresh()方法)。这里,“初始化”意味着加载所有bean,检测并激活后处理器bean,预先实例化单例,并且ApplicationContext对象准备好使用。只要上下文未关闭,只要所选的ApplicationContext实际上支持此类“热”刷新,就可以多次触发刷新。例如,XMLWebApplicationContext支持热刷新,但GenericApplicationContext不支持。
ContextStartedEvent 在可配置的ApplicationContext接口上使用start()方法启动ApplicationContext时发布。这里,“启动”意味着所有生命周期bean都会收到一个显式的启动信号。通常,此信号用于在显式停止后重新启动bean,但也可以用于启动尚未配置为自动启动的组件(例如,初始化时尚未启动的组件)。
ContextStoppedEvent 在可配置的ApplicationContext接口上使用stop()方法停止ApplicationContext时发布。这里,“停止”意味着所有生命周期bean都会收到一个明确的停止信号。停止的上下文可以通过start()调用重新启动。
ContextClosedEvent 在可配置的ApplicationContext接口上使用close()方法关闭ApplicationContext时发布。这里,“关闭”意味着所有的单例beans都被销毁了。封闭的环境达到了生命的尽头。无法刷新或重新启动。
RequestHandledEvent 一个特定于Web的事件,告诉所有bean HTTP请求已被服务。此事件在请求完成后发布。此事件仅适用于使用Spring的DispatcherServlet的Web应用程序。

基于继承的Event

你也可以自定义事件,下面是一个继承ApplicationEvent的例子:

  1. public class BlackListEvent extends ApplicationEvent {
  2. private final String address;
  3. private final String content;
  4. public BlackListEvent(Object source, String address, String content) {
  5. super(source);
  6. this.address = address;
  7. this.content = content;
  8. }
  9. }

若要发布自定义ApplicationEvent,在ApplicationEventPublisher上调用PublishEvent()方法。通常可以通过实现ApplicationEventPublisherAware接口来实现,如下所示:

  1. public class EmailService implements ApplicationEventPublisherAware {
  2. private List<String> blackList;
  3. private ApplicationEventPublisher publisher;
  4. public void setBlackList(List<String> blackList) {
  5. this.blackList = blackList;
  6. }
  7. public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
  8. this.publisher = publisher;
  9. }
  10. public void sendEmail(String address, String content) {
  11. if (blackList.contains(address)) {
  12. publisher.publishEvent(new BlackListEvent(this, address, content));
  13. return;
  14. }
  15. }
  16. }

在配置时,Spring容器检测到EmailService实现了ApplicationEventPublisherAware,并自动调用setApplicationEventPublisher()。实际上,传入的参数是Spring容器本身。您正在通过其applicationEventPublisher接口与应用程序上下文进行交互。

要接收定制的applicationEvent,可以创建一个实现applicationListener的类,并将其注册为SpringBean。下面的示例显示了这样的类:

  1. public class BlackListNotifier implements ApplicationListener<BlackListEvent> {
  2. private String notificationAddress;
  3. public void setNotificationAddress(String notificationAddress) {
  4. this.notificationAddress = notificationAddress;
  5. }
  6. public void onApplicationEvent(BlackListEvent event) {
  7. // notify appropriate parties via notificationAddress...
  8. }
  9. }

这里使用了ApplicationListener 的BlackListEvent泛型。意味着onApplicationEvent()方法可以保持类型安全,避免任何向下强制转换的需要。

但请注意,默认情况下,事件侦听器同步接收事件。这意味着publishEvent()方法将一直阻塞,直到所有侦听器完成对事件的处理。

下面是注册和配置bean的例子:

  1. <bean id="emailService" class="example.EmailService">
  2. <property name="blackList">
  3. <list>
  4. <value>known.spammer@example.org</value>
  5. <value>known.hacker@example.org</value>
  6. <value>john.doe@example.org</value>
  7. </list>
  8. </property>
  9. </bean>
  10. <bean id="blackListNotifier" class="example.BlackListNotifier">
  11. <property name="notificationAddress" value="blacklist@example.org"/>
  12. </bean>

Spring的事件机制是为同一应用程序上下文中SpringBean之间的简单通信而设计的。对于更复杂的企业集成需求,可以使用Spring Integration的AMQP模型来处理。

基于注解的Event

从Spring4.2开始,您可以使用EventListener注解在托管bean的任何公共方法上注册事件侦听器。BlackListNotifier程序可以改写如下:

  1. public class BlackListNotifierAnnotation {
  2. private String notificationAddress;
  3. public void setNotificationAddress(String notificationAddress) {
  4. this.notificationAddress = notificationAddress;
  5. }
  6. @EventListener
  7. public void processBlackListEvent(BlackListEvent event) {
  8. // notify appropriate parties via notificationAddress...
  9. }
  10. }

如果您的方法应该监听多个事件,或者您想要定义它而不使用任何参数,那么也可以在注解本身上指定事件类型。以下示例显示了如何执行此操作:

  1. @EventListener({ContextStartedEvent.class, ContextRefreshedEvent.class})
  2. public void handleContextStart() {
  3. }

还可以使用定义spEL表达式的注解的条件属性添加其他运行时筛选,该表达式应与实际调用特定事件的方法相匹配。

下面的例子显示了如何重写通知程序,以便仅在事件的内容属性等于my-event时调用:

  1. @EventListener(condition = "#blEvent.content == 'my-event'")
  2. public void processBlackListSPELEvent(BlackListEvent blEvent) {
  3. // notify appropriate parties via notificationAddress...
  4. }

下表列出了上下文可用的项,以便您可以将它们用于条件事件处理:

name Location 描述 例子
Event root object 真实的ApplicationEvent #root.event
Arguments array root object 调用目标的参数 #root.args[0]
Argument name evaluation context 任何方法参数的名称。如果由于某种原因,名称不可用(例如,因为没有调试信息),参数名称也可以在 #a<#arg>下使用,其中#arg表示参数索引(从0开始)。 #blEvent or #a0 (也可以使用 #p0 or #p<#arg>)

异步侦听器

如果希望特定的侦听器异步处理事件,可以重用常规的@Async支持。下面是@Async的例子:

  1. @Async
  2. @EventListener
  3. public void processBlackListEvent(BlackListEvent event) {
  4. // notify appropriate parties via notificationAddress...
  5. }

Listeners排序

如果需要先调用一个监听器,然后再调用另一个监听器,则可以将@order注解添加到方法声明中,如下所示:

  1. @EventListener
  2. @Order(12)
  3. public void processBlackListEvent(BlackListEvent event) {
  4. // notify appropriate parties via notificationAddress...
  5. }

本文的例子可以参考: event

更多教程请参考flydean的博客

Spring5参考指南:事件Event的更多相关文章

  1. Spring5参考指南:IOC容器

    文章目录 为什么使用Spring5 什么是IOC容器 配置元数据 实例化容器 XML嵌套 groovy bean定义DSL 使用容器 最近在翻译Spring Framework Documentati ...

  2. Spring5参考指南:基于注解的容器配置

    文章目录 @Required @Autowired @primary @Qualifier 泛型 @Resource @PostConstruct和@PreDestroy Spring的容器配置可以有 ...

  3. Spring5参考指南:容器扩展

    文章目录 BeanPostProcessor自定义bean BeanFactoryPostProcessor自定义配置元数据 使用FactoryBean自定义实例化逻辑 Spring提供了一系列的接口 ...

  4. Spring5参考指南:Bean的生命周期管理

    文章目录 Spring Bean 的生命周期回调 总结生命周期机制 startup和Shutdown回调 优雅的关闭Spring IoC容器 Spring Bean 的生命周期回调 Spring中的B ...

  5. Spring5参考指南:Bean作用域

    文章目录 Bean作用域简介 Singleton作用域 Prototype作用域 Singleton Beans 中依赖 Prototype-bean web 作用域 Request scope Se ...

  6. Spring5参考指南:依赖注入

    文章目录 依赖注入 依赖注入的配置详解 depends-on lazy-init 自动装载 方法注入 依赖注入 依赖注入就是在Spring创建Bean的时候,去实例化该Bean构造函数所需的参数,或者 ...

  7. Spring5参考指南:Bean的创建

    文章目录 Spring容器中的Bean Bean的命名 Bean的实例化 Spring容器中的Bean Bean在Spring中就是一个业务组件,我们通过创建各种Bean来完成最终的业务逻辑功能. 在 ...

  8. Spring5参考指南:AspectJ高级编程之Configurable

    文章目录 遇到的问题 @Configurable 原理 重要配置 遇到的问题 前面的文章我们讲到了在Spring中使用Aspect.但是Aspect的都是Spring管理的Bean. 现在有一个问题, ...

  9. Spring5参考指南:AOP代理

    文章目录 AOP代理 AOP Proxies原理 AOP代理 通常来说Spring AOP有两种代理方式,一种默认的JDK代理,只能代理接口,一种是CGLIB代理,可以代理具体的类对象. Spring ...

随机推荐

  1. C Cow XOR 奶牛异或

    时间限制 : 10000 MS   空间限制 : 65536 KB 问题描述 农民约翰在喂奶牛的时候被另一个问题卡住了.他的所有N(1 <= N <= 100,000)个奶牛在他面前排成一 ...

  2. Controller与RestController的区别

    在使用Spring系列的框架的时候,相信几乎所有人都会遇见@Controller与@RestController两个注解,那么这两个注解到底有什么区别? 1. 标记有@RestController的类 ...

  3. 3D城市

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  4. 【php】文件系统

    一. 了解文件: a) 我们在Windows当中已知众多种文件类型:png.jpeg.jpg.gif.mp3.mp4.avi.rmvb.txt.doc.exl.ppt.php.exe b) 无论我们w ...

  5. linux系统管理,查看系统资源

    free 查看内存使用情况 -b  ===>  以byte为单位 -k  ===>  以Kb为单位 -m  ===>  以Mb为单位 -g  ===>  以Gb为单位 -t  ...

  6. Nginx如何来配置隐藏入口文件index.php(代码)

    Nginx配置文件里放入这段代码 server { location / { index index.php index.html index.htm l.php; autoindex on; if ...

  7. Kubectl patch命令使用

    kubectl patch 使用(patch)补丁修改.更新资源的字段. 支持JSON和YAML格式. 请参阅https://htmlpreview.github.io/?https://github ...

  8. 生成3D多棱柱的方法(3D立体图片)

    先上一个效果图 主要运用的技术点就是 确认基点,确认每个盒子旋转的度数 3D变换  transform: rotateY(-360deg); 景深  perspective 3D舞台 transfor ...

  9. 2019-07-25【机器学习】无监督学习之聚类 K-Means算法实例 (1999年中国居民消费城市分类)

    样本 北京,2959.19,730.79,749.41,513.34,467.87,1141.82,478.42,457.64天津,2459.77,495.47,697.33,302.87,284.1 ...

  10. VXLAN 基础教程:在 Linux 上配置 VXLAN 网络

    上篇文章结尾提到 Linux 是支持 VXLAN 的,我们可以使用 Linux 搭建基于 VXLAN 的 overlay 网络,以此来加深对 VXLAN 的理解,毕竟光说不练假把式. 1. 点对点的 ...