当前位置 : 首页 » 文章分类 :  开发  »  Spring-Event

Spring-Event

Spring 事件

ApplicationContext 事件机制是观察者设计模式的实现,通过 ApplicationEvent 类和 ApplicationListener 接口,可以实现 ApplicationContext 事件处理;


ApplicationEvent 定义事件

  1. package org.springframework.context;
  2. import java.util.EventObject;
  3. public abstract class ApplicationEvent extends EventObject {
  4. private static final long serialVersionUID = 7099057708183571937L;
  5. private final long timestamp;
  6. public ApplicationEvent(Object source) {
  7. super(source);
  8. this.timestamp = System.currentTimeMillis();
  9. }
  10. public final long getTimestamp() {
  11. return this.timestamp;
  12. }
  13. }

Spring内置事件

Spring中ApplicationListener的使用
https://www.cnblogs.com/lwcode6/p/12072202.html


定义接收方

ApplicationListener 方式

  1. package org.springframework.context;
  2. import java.util.EventListener;
  3. @FunctionalInterface
  4. public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
  5. void onApplicationEvent(E event);
  6. }

实现 ApplicationListener 接口的 onApplicationEvent 方法

  1. @Component
  2. public class MyListener implements ApplicationListener<ContextRefreshedEvent> {
  3. public void onApplicationEvent(ContextRefreshedEvent event) {
  4. ...
  5. }
  6. }

onApplicationEvent 重复收到消息/被调用2次

问题:
同一条消息 onApplicationEvent 中收到2次

排查:
SimpleApplicationEventMulticaster 的 multicastEvent 中打断点,可以看到 getApplicationListeners(event, type) 返回的 listener 列表里,listener bean 出现了2次。

原因:
实现 ApplicationListener 接口的是个 抽象类,有两个具体实现类,所以注册了重复的 listener

Event Listeners in spring is called twice
https://stackoverflow.com/questions/21852474/event-listeners-in-spring-is-called-twice

@EventListener 方式

Better application events in Spring Framework 4.2
https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2

在任意

  1. @Component
  2. public class MyListener {
  3. @EventListener
  4. public void handleContextRefresh(ContextRefreshedEvent event) {
  5. ...
  6. }
  7. }

ApplicationEventPublisher 定义发送方

  1. package org.springframework.context;
  2. @FunctionalInterface
  3. public interface ApplicationEventPublisher {
  4. default void publishEvent(ApplicationEvent event) {
  5. publishEvent((Object) event);
  6. }
  7. void publishEvent(Object event);
  8. }

publishEvent(ApplicationEvent event)

利用 ApplicationContext 的 publishEvent() 方法,可以支持基于 Observer 模式的事件传播机制。

Spring中ApplicationContextAware使用说明
https://my.oschina.net/u/1407116/blog/276656


上一篇 sysbench-数据库基准测试工具

下一篇 Caffeine 缓存

阅读
评论
378
阅读预计1分钟
创建日期 2021-06-16
修改日期 2022-12-28
类别
标签

页面信息

location:
protocol: http:
host: devgou.com
hostname: devgou.com
origin: http://devgou.com
pathname: /article/Spring-Event/
href: http://devgou.com/article/Spring-Event/
document:
referrer:
navigator:
platform: Linux x86_64
userAgent: Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)

评论