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)

相关推荐
Yvonne爱编码2 分钟前
JAVA数据结构 DAY1-集合和时空复杂度
java·数据结构·python
win x18 分钟前
JavaSE(基础)高频面试点及 知识点
java·面试·职场和发展
Terio_my19 分钟前
简要 Java 面试题学习
java·开发语言·学习
好好研究1 小时前
Spring Boot - Thymeleaf模板引擎
java·spring boot·后端·thymeleaf
爬山算法1 小时前
Hibernate(76)如何在混合持久化环境中使用Hibernate?
java·后端·hibernate
编程彩机1 小时前
互联网大厂Java面试:从分布式缓存到消息队列的技术场景解析
java·redis·面试·kafka·消息队列·微服务架构·分布式缓存
她说..1 小时前
策略模式+工厂模式实现单接口适配多审核节点
java·spring boot·后端·spring·简单工厂模式·策略模式
坚持就完事了1 小时前
Java的OOP
java·开发语言
像少年啦飞驰点、1 小时前
零基础入门 Spring Boot:从“Hello World”到可部署微服务的完整学习路径
java·spring boot·微服务·编程入门·后端开发
undsky_2 小时前
【RuoYi-SpringBoot3-Pro】:将 AI 编程融入传统 java 开发
java·人工智能·spring boot·ai·ai编程