Lecture16-切面-[实验05]环绕通知

文章目录

    [toc]

    单词词性音标含义
    proceedv./prəˈsiːd/继续;执行(AOP环绕通知中,ProceedingJoinPoint.proceed()方法用于调用目标方法,使增强逻辑可在目标方法执行前后插入)
    Signaturen./ˈsɪɡnətʃə(r)/签名(表示方法的特征信息,包含方法名、参数类型、返回值类型及所属类等,可通过连接点获取)

    Lecture16-切面-[实验05]环绕通知

    0、复习 try{} catch(){} finally{}

    try {
        
        // 尝试执行有可能抛异常的代码
        // 目标核心操作
        
    }catch(异常类型 变量){
        
        // 真抛异常的时候,执行的备选方案
        
    }finally{
        
        // 不管是否抛异常都会执行的部分
        
    }
    

    1、语法要点

    • 使用@Around注解声明环绕通知
    • 使用ProceedingJoinPoint参数获取目标方法细节
    • 通过调用ProceedingJoinPoint的proceed()方法调用目标方法
    • 环绕通知方法内部通常使用 try...catch...finally 结构编写代码
    • 环绕通知一定要记得把目标方法的返回值返回

    2、示例代码

    // 使用@Around注解标明环绕通知方法
    @Around(value = "com.atguigu.aop.aspect.AtguiguPointCut.transactionPointCut()")
    public Object manageTransaction(
        
            // 通过在通知方法形参位置声明ProceedingJoinPoint类型的形参,
            // Spring会将这个类型的对象传给我们
            ProceedingJoinPoint joinPoint) {
        
        // 通过ProceedingJoinPoint对象获取外界调用目标方法时传入的实参数组
        Object[] args = joinPoint.getArgs();
        
        // 通过ProceedingJoinPoint对象获取目标方法的签名对象
        Signature signature = joinPoint.getSignature();
        
        // 通过签名对象获取目标方法的方法名
        String methodName = signature.getName();
        
        // 声明变量用来存储目标方法的返回值
        Object targetMethodReturnValue = null;
        
        try {
        
            // 在目标方法执行前:开启事务(模拟)
            System.out.println("[AOP 环绕通知] 开启事务,方法名:" + methodName + ",参数列表:" + Arrays.asList(args));
        
            // 过ProceedingJoinPoint对象调用目标方法
            // 目标方法的返回值一定要返回给外界调用者
            targetMethodReturnValue = joinPoint.proceed(args);
        
            // 在目标方法成功返回后:提交事务(模拟)
            System.out.println("[AOP 环绕通知] 提交事务,方法名:" + methodName + ",方法返回值:" + targetMethodReturnValue);
        
        }catch (Throwable e){
        
            // 在目标方法抛异常后:回滚事务(模拟)
            System.out.println("[AOP 环绕通知] 回滚事务,方法名:" + methodName + ",异常:" + e.getClass().getName());
        
        }finally {
        
            // 在目标方法最终结束后:释放数据库连接
            System.out.println("[AOP 环绕通知] 释放数据库连接,方法名:" + methodName);
        
        }
        
        return targetMethodReturnValue;
    }
    
    end