Spring AOP 各种通知

1. 前置通知

    /*
       1.前置通知在目标类的目标方法执行之前执行
       2.前置通知可以获取目标类和目标方法的相关信息.
        <aop:before method="before" pointcut-ref="demo"/>
     */
    public void before(JoinPoint joinPoint) {
        String classSimpleName = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("classSimpleName:" + classSimpleName);
        System.out.println("methodName:" + methodName);
        System.out.println(Arrays.toString(args));
        System.out.println("before method");
    }

2. 后置通知

   /*
        1.后置通知在目标类的目标方法正常返回之后执行.
            >>必须是正常返回,也就是说,如果抛了异常.则后置通知不执行
        2.后置通知可以通过在xml中设置returning属性获取返回值
        <aop:after-returning method="after" pointcut-ref="demo" returning="ret"/>
     */
    public void after(JoinPoint joinPoint,Object ret){
        System.out.println("return object:"+ ret);
        System.out.println("after method");
    }

3. 最终通知

    /*
        1. 最终通知:无论是否抛异常在调用目标方法后都执行.并且执行顺序来看在后置通知之后
        <aop:after method="finallyMethod" pointcut-ref="demo" />
     */
    public void finallyMethod(JoinPoint joinPoint){
        System.out.println("invoke anymore");
    }

4. 异常通知

    /*
        1.异常通知:当目标方法抛出异常的时候被调用.并且执行顺序在最终通知之后
        <aop:after-throwing method="afterThrowing" pointcut-ref="demo" throwing="ex"/>
     */
    public void afterThrowing(JoinPoint joinPoint,Throwable ex){
        System.out.println(ex.getMessage());
    }

5.最终通知

    /*
        1.环绕通知能控制目标方法的执行
     */
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("before");
        Object ret = joinPoint.proceed();
        System.out.println("return value:" + ret);
        System.out.println("after");
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值