- 定义DoTransactionCompletion
import org.springframework.transaction.support.TransactionSynchronization; public class DoTransactionCompletion implements TransactionSynchronization { private Runnable runnable; public DoTransactionCompletion(Runnable runnable) { this.runnable = runnable; } /** * 事务完成后的回调方法 * @param status */ @Override public void afterCompletion(int status) { if(status == TransactionSynchronization.STATUS_COMMITTED){ runnable.run(); } } }
- 定义TransactionUtils
import org.springframework.transaction.support.TransactionSynchronizationManager; public class TransactionUtils { public static void doAfterTransaction(DoTransactionCompletion doTransactionCompletion){ if(TransactionSynchronizationManager.isActualTransactionActive()){ TransactionSynchronizationManager.registerSynchronization(doTransactionCompletion); } } }
- 使用TransactionUtils
@Test @Transactional @Rollback(false) //单元测试默认不提交事务,此注解强制提交事务 public void doTx(){ //开始事务 System.out.println("开始事务"); TransactionUtils.doAfterTransaction(new DoTransactionCompletion(() -> { //事务执行完后回调的方法,例如 发送一个MQ,RPC等操作 System.out.println("事务执行完后回调的方法"); })); //结束事务 System.out.println("结束事务"); } }