事务提交后再执行异步(@Async)任务的完整代码示例

📅 2026/6/30 11:28:42
事务提交后再执行异步(@Async)任务的完整代码示例
好两种都给你直接复制用方式一控制层写法全部在 ControllerRestControllerRequestMapping(/api/test)publicclassTestController{AutowiredprivateTransactionTemplatetransactionTemplate;AutowiredprivateTStudentTestServicetStudentTestService;AutowiredprivateNoticeServicenoticeService;GetMapping(/list1)publicRlist1(){transactionTemplate.execute(status-{// 注册事务同步回调TransactionSynchronizationManager.registerSynchronization(newTransactionSynchronization(){OverridepublicvoidafterCommit(){// 事务提交后才执行异步方法noticeService.studentTest();}});// 批量插入数据for(inti0;i1000;i){TStudentTesttStudentTestnewTStudentTest();tStudentTest.setCreateBy(123);tStudentTest.setCreateTime(newDate());tStudentTest.setContent();tStudentTest.setName(测试服);tStudentTest.setSex(1);tStudentTest.setAge(22l);tStudentTest.setType(TStudentTestTypeEnum.SJ.getValue());tStudentTestService.save(tStudentTest);}System.out.println(保存System.currentTimeMillis());returnnull;});returnR.ok();}}方式二业务层写法Controller 调 Service1. 控制层RestControllerRequestMapping(/api/test)publicclassTestController{AutowiredprivateTestServicetestService;GetMapping(/list1)publicRlist1(){testService.batchInsert();returnR.ok();}}2. 业务层ServicepublicclassTestService{AutowiredprivateTransactionTemplatetransactionTemplate;AutowiredprivateTStudentTestServicetStudentTestService;AutowiredprivateNoticeServicenoticeService;publicvoidbatchInsert(){transactionTemplate.execute(status-{// 注册事务同步回调TransactionSynchronizationManager.registerSynchronization(newTransactionSynchronization(){OverridepublicvoidafterCommit(){// 事务提交后才执行异步方法noticeService.studentTest();}});// 批量插入数据for(inti0;i1000;i){TStudentTesttStudentTestnewTStudentTest();tStudentTest.setCreateBy(123);tStudentTest.setCreateTime(newDate());tStudentTest.setContent();tStudentTest.setName(测试服);tStudentTest.setSex(1);tStudentTest.setAge(22l);tStudentTest.setType(TStudentTestTypeEnum.SJ.getValue());tStudentTestService.save(tStudentTest);}System.out.println(保存System.currentTimeMillis());returnnull;});}}共用异步任务层ServiceSlf4jpublicclassNoticeService{AsyncpublicvoidstudentTest(){System.out.println(异步执行System.currentTimeMillis());}}启动类SpringBootApplicationEnableAsyncpublicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}}