参考gitee:

https://gitee.com/liushanshan126/listener-test

一、实现步骤

  1. 创建一个实体类,继承ApplicationEvent类

  2. 再某一处实现代码里面,先注入下图代码,再发布事件,使用代码
    applicationContext.publishEvent(继承了ApplicationEvent类的子类)

  3. 在component层,创建一个方法,方法上写入
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)注解,方法里面入参为继承了ApplicationEvent类的子类

    @Resource
    private ApplicationContext applicationContext;

二、为什么使用spring的监听器,有什么好处

  1. 使代码解耦
  2. 可以使用spring监听器的异步功能,与主线程同步执行代码
  3. 加入@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)这一句话,会想让数据库进行提交后,再执行监听器内容。
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐