023Spring事件机制

本文详细介绍了Spring框架中的事件机制,包括内置事件如ContextRefreshedEvent、ContextClosedEvent等,以及如何自定义事件和实现监听器。通过实现ApplicationListener接口并使用ApplicationContext的publishEvent方法,可以实现事件和监听器的解耦。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

事件

Spring内置事件:

  • ContextRefreshedEvent: ApplicationContext容器初始化或者刷新触发
  • ContextClosedEvent: 调用ConfigurableApplicationContext(ApplicationContext子接口)的 close()方法时触发
  • ContextStartedEvent: 调用ConfigurableApplicationContext(ApplicationContext子接口)的 start()方法时触发
  • ContextStoppedEvent: 调用ConfigurableApplicationContext(ApplicationContext子接口)的 stop()方法时触发
  • RequestHandledEvent: web相关,当Spring处理用户请求后触发

自定义事件:
只需要让该类继承ApplicationEvent就行。

监听器

写一个监听器类很简单,只需要让该类实现ApplicationListener接口,并且实现接口中的方法 onApplicationEvent(ApplicationEvent evt),然后把这个类添加到Spring容器中作为bean对象,Spring会自动检查所有的bean,如果bean实现ApplicationListener接口,那么Spring中的触发事件就会被传递给该监听器(也就是自动调用该监听器的onApplicationEvent方法)。获得事件对象后就可以完成相应的相应操作。

触发事件

上述的内置事件是在特定的时机自动触发,自定义的事件需要手动触发:
利用ApplicationContext的 publishEvent(ApplicationEvent evt)方法来触发(向Spring容器发布事件),Spring拿到事件之后传递给Spring容器中的监听器。
这就完成了事件和监听器的解耦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值