spring-aop 的 基础使用 - 4 - 环绕通知 @Around

文章目录

      • TxAroundAdvice.java
      • [简化了前面 4种(@Before、@AfterReturning、@AfterThrowing、@After)](#简化了前面 4种(@Before、@AfterReturning、@AfterThrowing、@After))

在 spring-aop 的 基础使用 -3 - 切点表达式 的提取、复用

的基础上,在看这个文章

TxAroundAdvice.java

java 复制代码
package com.english.advice;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 环绕通知 @Around,
 *      对应整个 try...catch...finally 结构,
 *      它包括,前面4种通知的所有功能,
 *      前面4种通知:
 *          前置  @Before
 *          后置  @AfterReturning
 *          异常  @AfterThrowing
 *          最后  @After
 */

@Aspect
@Component
public class TxAroundAdvice {

    // 这里的 ProceedingJoinPoint joinPoint 比前面说到的,获取目标方法的信息JoinPoint joinPoint,多了一个触发目标方法执行的方法proceed()
    @Around("com.english.pointcut.MyPointCut.mypc()")
    public Object around(ProceedingJoinPoint joinPoint) {
        // 保证目标方法被执行
        Object[] args =  joinPoint.getArgs();
        Object result = null;

        try {
            // 增强代码 -> Before
            System.out.println("开启事务");

            // 触发目标方法的执行
            result = joinPoint.proceed(args);

            System.out.println("结束事务");
        } catch (Throwable e) {
            System.out.println("事务回滚");
            throw new RuntimeException(e);
        } finally {

        }

        return result;
    }
}

简化了前面 4种(@Before、@AfterReturning、@AfterThrowing、@After)

相关推荐
EatFan4 小时前
Spring Boot 4 落地观察:从 yudao-cloud、matecloud、JPower 看国产脚手架的升级路线与迁移清单
java·spring boot·后端·spring cloud·微服务·后端开发·jdk 21
Maiko Star4 小时前
* LangChain 提示词模板详解:ChatPromptTemplate 的使用与高级特性
java·人工智能·langchain
现任明教教主~6 小时前
Thinkphp站群蜘蛛池SaaS系统YanyvSEO含多用户/积分/六大引擎计费/易支付对接
java·开发语言·spring
一条破秋裤7 小时前
Linux 线程创建:pthread_create 与基本回收
java·linux·运维
布吉岛的石头7 小时前
Java 程序员第 49 阶段5:BERT 预训练目标 MLM+NSP 的工程含义
java·人工智能·深度学习·bert·transformer
摇滚侠8 小时前
《On Java 中文版 基础卷》阅读笔记 对象无处不在 03
java·笔记·python
二十雨辰8 小时前
[学成在线]-01项目背景
java
弈栈录9 小时前
Java AI 应用的异步化与高并发设计
java·后端·架构
落魄实习生9 小时前
Agent Scope Java 2.x 系列【2】 ReActAgent
java·开发语言
艸肅9 小时前
Ubuntu 安装 JDK (含手动安装)
java·ubuntu·jdk