1. TransactionalEventListener注解介绍TransactionalEventListener 注解常用于标记一个事件监听方法当指定的事务阶段完成时会触发该事件。它是 EventListener 的扩展专门用于处理事务相关的事件。phase 属性用于指定事务事件监听的阶段。常见的选项包括TransactionPhase.BEFORE_COMMIT事务提交之前触发。TransactionPhase.AFTER_COMMIT事务成功提交之后触发。TransactionPhase.AFTER_ROLLBACK事务回滚之后触发。TransactionPhase.AFTER_COMPLETION事务完成无论是提交还是回滚之后触发。必须在带有Transactional注解的方法中发布事件才能触发TransactionalEventListener。如果事件发布方法没有事务则事务事件监听器不会被触发。TransactionalEventListener自身不需要Transactional但需要事件发布的上下文有事务管理。2. 监听类GetterpublicclassCommitEventextendsApplicationEvent{privateStringeventValue;privateObjectpayload;publicCommitEvent(Objectsource,StringeventValue,Objectpayload){super(source);this.eventValueeventValue;this.payloadpayload;}}3. 添加事务RestControllerSlf4jpublicclassDemoController{AutowiredprivateDemoServicedemoService;GetMapping(/update)publicResponseEntityStringupdate(Peoplepeople){demoService.updateFtp(people);returnResponseEntity.ok(success);}}ServicepublicclassDemoService{AutowiredprivateApplicationEventPublisherapplicationEventPublisher;AutowiredprivatePeopleMapperpeopleMapper;TransactionalpublicvoidupdateFtp(Peoplepeople){// 1. 执行用户更新逻辑更新到数据库peopleMapper.update(people);// 2. 发布用户更新事件此时事务尚未提交applicationEventPublisher.publishEvent(this,test01,test);}}4. 事务事件监听类Slf4jComponentpublicclassDemoListener{AsyncTransactionalEventListener(condition#commitEvent.eventValue test01,phaseTransactionPhase.AFTER_COMMIT)publicvoidafterDataBaseCommit(CommitEventcommitEvent){log.info(afterDataBaseCommit : commitEvent {} ,commitEvent);}}