您的位置:首页 > 编程语言 > Java开发

《Spring AOP》-----各种通知解析

2016-11-25 08:41 169 查看

前言

上一篇文章中,小编简单介绍了SpringAop中的一些概念,意义、还有简单入门的小例子,那么现在小编带着读者解析一下SpringAop中的几种通知,所谓的通知,就是切面中的几种方法。

1、前置通知(切面类方法)

/*
* 在目标方法执行之前执行
* 参数:连接点
*/
public void beginTransaction(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
System.out.println("连接点的名称:"+methodName);
System.out.println("目标类:"+joinPoint.getTarget().getClass());
System.out.println("begin transaction");
}


配置文件

<aop:before method="beginTransaction" pointcut-ref="perform"/>


2、后置通知(切面类方法)

/**
*     在目标方法执行之后执行
*     参数:连接点、目标方法返回值
*/
public void commit(JoinPoint joinPoint,Object val){
System.out.println("目标方法的返回值:"+val);
System.out.println("commit");
}


配置文件

<!--
1、后置通知可以获取到目标方法的返回值
2、当目标方法抛出异常,后置通知将不再执行
-->
<aop:after-returning method="commit" pointcut-ref="perform" returning="val"/>


3、最终通知(切面类方法)

public void finallyMethod(){
System.out.println("finally method");
}


配置文件

<!--
无论目标方法是否抛出异常都将执行
-->
<aop:after method="finallyMethod" pointcut-ref="perform"/>


4、异常通知(切面类方法)

/**
*    接受目标方法抛出的异常
*    参数:连接点、异常
*/
public void throwingMethod(JoinPoint joinPoint,Throwable ex){
System.out.println(ex.getMessage());
}


配置文件

<!--
异常通知
-->
<aop:after-throwing method="throwingMethod" throwing="ex" pointcut-ref="perform"/>


5、环绕通知(切面类方法)

/**
*   joinPoint.proceed();这个代码如果在环绕通知中不写,则目标方法不再执行
*  参数:ProceedingJoinPoint
*/
public void aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("aaaa");
joinPoint.proceed();//调用目标方法
}


配置文件

<!--
能控制目标方法的执行
-->
<aop:around method="aroundMethod" pointcut-ref="perform"/>


小结:

前置通知是在目标方法执行之前执行;后置通知是在目标方法执行之后执行,但是目标方法如果有异常,后置通知不在执行;而最终通知无论目标方法有没有异常都会执行;异常通知是捕获异常使用的;环绕通知能控制目标方法的执行。这就是以上的几种通知。小编将配置文件简单化,如果读者想拿代码测试一下的话,可以结合着Spring

Aop入门将代码补全。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring aop