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)

相关推荐
Java面试题总结5 小时前
java高频面试题(2026最新)
java·开发语言·jvm·数据库·spring·缓存
苦逼的猿宝5 小时前
学生心理咨询评估系统
java·毕业设计·springboot·计算机毕业设计
隔窗听雨眠5 小时前
doctype、charset、meta如何控制整个渲染流水线
java·服务器·前端
西安邮电大学6 小时前
SpringBean完整生命周期
java·spring
刀法如飞6 小时前
DDD 与 Ontology 对比分析:哪一种更适合AI时代复杂系统构建?
java·架构·领域驱动设计
SunnyDays10117 小时前
Java 读写 Excel 公式:从基础到高级的实战总结
java·开发语言·excel
wb043072017 小时前
Java 26
java·开发语言
白露与泡影7 小时前
JVM GC调优实战:从线上频繁Full GC到RT降低80%的全过程
java·开发语言·jvm
范什么特西7 小时前
Spring 动态代理 静态代理
java·后端·spring
醇氧7 小时前
Spring 动态注册 Bean 深度解析:从源码到实践
java·后端·spring