• 13Spring_AOP编程(AspectJ)_后置通知


    后置通知和前置通知差不多。最大的特点是因为后置通知是运行在目标方法之后的,所以他可以拿到目标方法的运行的结果。

    给出案例:

    案例结构图:

    其实和上一篇的前置通知差不多,这里每个类就不做具体解释了。

    第一步:

    编写目标类:

    package cn.itcast.spring.d_aspectj;
    
    //目标业务类
    public class CustomerService {
        
    
        public int delete() {
            System.out.println("this is delete");
            return 1;
        }
    
        
    
    }

    第二步:

    编写切面类

    //切面类(内部可以写很多的Advice的方法)
    public class MyAspect {
        
        //可以传两个参数,后置通知相比前置通知来时
        //一个特点是,因为后置通知是运行在目标方法之后的,所以他可以拿到目标方法的运行的结果
        public void afterReturning(JoinPoint joinPoint,Object result)
        {
            System.out.print("后置通知的运行"+result);
            
        }
    
    }

    第三步:编写Spring配置文件

    <!-- AspectJ AOP -->
    <!-- 配置目标 -->
    <bean id="CustomerService" class="cn.itcast.spring.d_aspectj.CustomerService"></bean>
     <!-- 配置切面类 -->
    <bean id="MyAspect" class="cn.itcast.spring.d_aspectj.MyAspect"></bean>
     <aop:config>
     <!-- ref引用切面类 -->
     <aop:aspect ref="MyAspect">
     
         <aop:pointcut expression="execution(* cn.itcast.spring.d_aspectj.CustomerService.*(..))" id="mypointcut2"/>
       
          
          <!-- 这个参数是配置返回的   必须和public void afterReturning(JoinPoint joinPoint,Object result)这个方法里面的 result一字不差-->
          <aop:after-returning method="afterReturning" returning="result" pointcut-ref="mypointcut2"  />
     </aop:aspect>

    第三步:编写测试类

        @Test
        public void testafter()
        {System.out.print(customerService.getClass().getName());
            customerService.delete();
            
        }

    输出结果:

    this is delete
    后置通知的运行1

    看到没  !返回了目标函数的执行结果。

  • 相关阅读:
    8.Nginx常用基础模块
    7.Web基础之Nginx
    6.Web基础之http协议
    5.SSH远程服务
    4.Sersync实时同步
    3.NFS 共享存储
    前端-CSS
    前端-HTTP
    MySQL-其他知识点
    MySQL-pymysql模块
  • 原文地址:https://www.cnblogs.com/shenxiaoquan/p/5713237.html
Copyright © 2020-2023  润新知