日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

事务框架之声明事务(自动开启,自动提交,自动回滚)Spring AOP 封装

發布時間:2025/5/22 71 豆豆
生活随笔 收集整理的這篇文章主要介紹了 事务框架之声明事务(自动开启,自动提交,自动回滚)Spring AOP 封装 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

利用Spring AOP 封裝事務類,自己的在方法前begin 事務,完成后提交事務,有異常回滾事務

比起之前的編程式事務,AOP將事務的開啟與提交寫在了環繞通知里面,回滾寫在異常通知里面,找到指定的方法(切入點),代碼如下:

代碼在這個基礎上重構:

?https://www.cnblogs.com/pickKnow/p/11135310.html

@Component @Aspect
@Scope("prototype")
public class AopTransaction {@Autowiredprivate TransactionUtils transactionUtils;@Around("execution (* com.hella.thread.aoptransaction.service.UserService.addUser(..) )")public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {//不要try catch 不然回滾不了,一直占用資源System.out.println("開啟事務");TransactionStatus transactionStatus = transactionUtils.begin();proceedingJoinPoint.proceed();transactionUtils.commit(transactionStatus);System.out.println("提交事務");}@AfterThrowing("execution (* com.hella.thread.aoptransaction.service.UserService.addUser(..) )")public void afterThrowing() {System.out.println("事務開始回滾"); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); }}

?

那service 層方法里面就不需要再寫事務的開啟,提交,回滾了。

@Service public class UserServiceImpl implements UserService {@Autowiredprivate UserDao userDao;@Overridepublic void addUser() {// 添加到數據庫System.out.println("開始添加");userDao.add(1, "tom", "12");} }

?

轉載于:https://www.cnblogs.com/pickKnow/p/11138118.html

總結

以上是生活随笔為你收集整理的事务框架之声明事务(自动开启,自动提交,自动回滚)Spring AOP 封装的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。