利用Spring AOP 封裝事務類,自己的在方法前begin 事務,完成后提交事務,有異常回滾事務
比起之前的編程式事務,AOP將事務的開啟與提交寫在了環繞通知里面,回滾寫在異常通知里面,找到指定的方法(切入點),代碼如下:
代碼在這個基礎上重構:
https://www.cnblogs.com/pickKnow/p/11135310.html
@Component @Aspect
@Scope("prototype") public class AopTransaction { @Autowired private 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 { @Autowired private UserDao userDao; @Override public void addUser() { // 添加到數據庫 System.out.println("開始添加"); userDao.add(1, "tom", "12"); } }