spring aop 五大通知类型

1、定义

1、before(前置通知):在连接点方法之前执行,不能控制连接点方法是否执行。

2、after(后置通知):又名最终通知,连接点方法只要执行,不管会不会出现错误,它最后都会被执行。

3、after-return(返回通知):连接点正常执行,并且不会报错才会执行。

4、throwing(异常通知):连接点方法抛出异常时才会执行,这个通知不能处理异常,只能得到异常信息,异常通知如果想要把目标方法抛出的异常传递给通知方法,只要在异常通知的throwing属性设置等于通知方法的参数名即可。 如果没有设置异常类型,目标方法抛出任何异常,此通知不执行,后面的通知都会执行。 有设置异常类型做参数,目标方法抛出的异常是通知方法参数的指定类型异常或子类型时,此通知方法才会得到执行。

5、around(环绕通知):结合了上面四种通知,加强版的通知,可以实现上面四种通知的功能。

2、before(前置通知)

after和after-return和前置通知差不多,就不做解释了。

普通前置通知

<aop:before method="BeforeInsert" pointcut-ref="studentPointcut"/>
//通知方法
public
void BeforeInsert(JoinPoint joinPoint){ System.out.println(joinPoint); System.out.println("BeforeInsert as LogImpl"); }

通知方法可以选择是否带参数,可带JoinPoint参数,这个参数包含了连接点的一些信息。

我们也可以在这里获取连接点方法的参数值。

连接点

public int add(int num1,int num2){
    return num1+num2;
}

通知

public void beforeInsert(JoinPoint joinPoint,int n,int m){
    System.out.println(n);
    System.out.println(m);
    System.out.println(joinPoint);
    System.out.println("BeforeInsert as LogImpl");
}

xml

<aop:config>
    <!--切点表达式中添加and 设置别名,可以设置和通知方法的参数名一样的-->
        <aop:pointcut id="studentPointcut" expression="execution(* com.target.StudentDaoImpl.*(..)) and args(n,m)"/>
        <aop:aspect id="logAspect" ref="log">
            <!--arg-names对应切点表达式的别名-->
            <aop:before method="beforeInsert" pointcut-ref="studentPointcut" arg-names="n,m"/>
        </aop:aspect>
</aop:config>

切点表达式设置了args(n,m),那么其它通知也需要添加对应的方法参数和设置arg-names

3、throwing(异常通知)

<aop:after-throwing method="throwInsert" pointcut-ref="studentPointcut" throwing="ey"/>

throwing指定异常类型参数

public void throwInsert(RuntimeException ey) {
    System.out.println("throwException");
}

如果异常通知方法没有设置异常参数,throwing不用设置参数,目标方法产生的所有异常都会使用此通知方法

异常通知方法设置了异常参数,throwing需要设置跟异常参数,目标方法产生的异常是此通知异常类型或子类型时,该通知方法才会被使用。

4、around(环绕通知)

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

通知方法:

public Object aroundInsert(ProceedingJoinPoint joinPoint){
    //相当于before
    System.out.println("Before....");
    //定义result保存调用方法结果
    Object result = null;
    try {
        //调用方法
        result = joinPoint.proceed();
        //相当于after-return
        System.out.println("after-return....");
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        //相当于throwing
        System.out.println("throwing....");
    }
    //相当于after
    System.out.println("after....");
    //返回结果
    return result;
}

around一般使用比较多,因为它包含了上面四种的功能。

ProceedingJoinPoint 一般作为环绕通知方法的参数,它实现了JoinPoint接口,增强版。可以控制目标方法的执行

以及查看目标方法的参数等等。

JoinPoint作为上面四种通知的参数。它包含了一系列的目标方法的信息。

原文地址:https://www.cnblogs.com/liweixml/p/11789075.html