• 基于XML的AOP配置(2)-环绕通知


    配置方式:
    <aop:config>
        <aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))"
      id="pt1"/>
      <aop:aspect id="txAdvice" ref="txManager">
        <!-- 配置环绕通知 -->
        <aop:around method="aroundPrint" pointcut-ref="pt1"/>
      </aop:aspect>
    </aop:config>
    aop:around:
    作用:
    用于配置环绕通知
    属性:
    method:指定通知中方法的名称。
    pointct:定义切入点表达式
    pointcut-ref:指定切入点表达式的引用
    说明:
    它是 spring 框架为我们提供的一种可以在代码中手动控制增强代码什么时候执行的方式。
    注意:
    通常情况下,环绕通知都是独立使用的
    /**
         * 环绕通知
         * 问题:
         *     当我们配置了环绕通知后,切入点方法不执行,而通知方法执行了
         * 分析:
         *     通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用而我们的代码中没有
         * 解决:
         *     Spring框架为我们提供ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法
         *     该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用
         * */
        public Object aroundPrint(ProceedingJoinPoint pjp){
            try {
                Object args[] = pjp.getArgs();//得到方法执行所需要的参数
                System.out.println("环绕通知logger开始记录日志了前置");
                Object returnValue = pjp.proceed();//明确调用业务层(切入点方法)
                System.out.println("环绕通知logger开始记录日志了后置");
                return returnValue;
            } catch (Throwable throwable) {
                System.out.println("环绕通知logger开始记录日志了异常");
                throw new RuntimeException(throwable);
            }finally {
                System.out.println("环绕通知logger开始记录日志了最终");
            }
        }

  • 相关阅读:
    JavaSE基础day23 死锁、线程生命周期、枚举
    JavaSE基础day21 Thread类
    JavaSE基础day20 多线程3种实现方式
    JavaSE基础day22 线程安全问题、锁
    JavaSE基础day24 枚举常用方法、反射
    使用Blazor开发WinForm程序
    Blazor使用PDFObject预览pdf文件
    kubernetes的原理和使用
    docker的产生及应用
    JVM:方法区、堆
  • 原文地址:https://www.cnblogs.com/qzhc/p/11971772.html
Copyright © 2020-2023  润新知