分享知识-快乐自己:Spring切入点的表达式和通知类型

1.切入点的表达式

表达式格式:

execution([修饰符] 返回值类型 包名.类名.方法名(参数))

其他的代替:

复制代码
<!-- 完全指定一个方法 -->
<!-- <aop:before method="log" pointcut="execution(public void com.spring.demo1.UserServiceImpl.save())"/> -->        

<!-- 修饰符可以不写,不是必要出现的 -->
<!-- <aop:before method="log" pointcut="execution(void com.spring.demo1.UserServiceImpl.save())"/> -->

<!-- 返回值类型必须写,可以用【*】代替 -->
<!-- <aop:before method="log" pointcut="execution(* com.spring.demo1.UserServiceImpl.save())"/> -->

<!-- 包名必须写,可以用【*】代替 -->
<!-- <aop:before method="log" pointcut="execution(* *.spring.demo1.UserServiceImpl.save())"/> -->

<!-- 任意包结构,【*..*】 -->
<!-- <aop:before method="log" pointcut="execution(* *..*.UserServiceImpl.save())"/> -->

<!-- 类必须写,可以用【*】代替 -->
<!-- <aop:before method="log" pointcut="execution(* *..*.*ServiceImpl.save())"/> -->

<!-- 方法必须写,可以用【*】代替 -->
<!-- <aop:before method="log" pointcut="execution(* *..*.*ServiceImpl.save*())"/> -->

<!-- 参数必须写,【*】代表一个参数,【..】代表任意参数 -->
<!-- <aop:before method="log" pointcut="execution(* *..*.*ServiceImpl.save*(..))"/> -->
复制代码

2.AOP通知类型

1. 前置通知:
      * 在目标类的方法执行之前执行。
      * 配置文件信息:

<aop:after method="before" pointcut-ref="myPointcut3"/>

* 应用:可以对方法的参数来做校验


2. 最终通知:
        * 在目标类的方法执行之后执行,如果程序出现了异常,最终通知也会执行。
        * 在配置文件中编写具体的配置:

<aop:after method="after" pointcut-ref="myPointcut3"/>

* 应用:例如像释放资源


3. 后置通知:
        * 方法正常执行后的通知。        
        * 在配置文件中编写具体的配置:

<aop:after-returning method="afterReturning" pointcut-ref="myPointcut2"/>

* 应用:可以修改方法的返回值


4. 异常抛出通知:
        * 在抛出异常后通知
        * 在配置文件中编写具体的配置:

<aop:after-throwing method="afterThorwing" pointcut-ref="myPointcut3"/>

* 应用:包装异常的信息


5. 环绕通知:
        * 方法的执行前后执行。
        * 在配置文件中编写具体的配置:

<aop:around method="around" pointcut-ref="myPointcut2"/>

 * 要注意:目标的方法默认不执行,需要使用ProceedingJoinPoint对来让目标对象的方法执行。

复制代码
    public void around(ProceedingJoinPoint joinPoint){
        System.out.println("环绕通知1...");
        try {
            // 手动让目标对象的方法去执行
            joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("环绕通知2...");
    }
复制代码

 转载请跟随-注:(https://www.cnblogs.com/NEWHOM/p/6803307.html)

原文地址:https://www.cnblogs.com/mlq2017/p/9629591.html