spring事件监听

第一章 spring框架构成
第二章 spring容器
第三章 spring配置bean
第四章 bean的继承和依赖
第五章 bean的生命周期
第六章 spring依赖注入
第七章 Spring AOP
第八章 spring事务
第九章 spring事件监听



原文链接 https://zhhll.icu/2021/框架/spring/基础/9.spring事件监听/

spring事件监听

ApplicationListener监听容器中发布的事件

实现ApplicationListener来完成事件监听

public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

   /**
    * Handle an application event.
    * @param event the event to respond to
    */
   void onApplicationEvent(E event);

}

spring中定义的事件

Spring 提供了以下 5 中标准的事件:

  • 上下文更新事件ContextRefreshedEvent

    该事件会在ApplicationContext 被初始化或者刷新时发布。也可以在调用 ConfigurableApplicationContext 接口中的 refresh()方法时被触发

  • 上下文开始事件ContextStartedEvent

    当容器调用ConfigurableApplicationContext的 Start()方法开始/重新开始容器时触发该事件

  • 上下文停止事件ContextStoppedEvent

    当容器调用 ConfigurableApplicationContext的 Stop()方法停止容器时触发该事件

  • 上下文关闭事件ContextClosedEvent

    当容器调用 ConfigurableApplicationContext的close()方法关闭ApplicationContext时触发该事件。容器被关闭时,其管理的所有单例 Bean 都被销毁

  • 请求处理事件RequestHandledEvent

    在 Web 应用中,当一个 http 请求(request)结束触发该事件

spring的事件处理是单线程的,当事件被发布时,该进程会阻塞直到所有的接收者得到该消息

自定义事件监听器

可以实现ApplicationListener来自定义事件,如果一个 bean 实现了 ApplicationListener 接口,当一个 ApplicationEvent 被发布以后,bean 会自动被通知

@Component
public class UserLogListener implements ApplicationListener<UserEvent> {

    private final UserEventLogService userEventLogService;

    @Override
    public void onApplicationEvent(UserEvent userEvent) {
        // 处理事件
    }

}

事件需要继承ApplicationEvent

public class UserEvent extends ApplicationEvent {

}

可以使用publishEvent方法来发布事件

ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig4.class);

context.publishEvent(new UserEvent() {
        });
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拾光师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值