《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"/>
小结:
前置通知是在目标方法执行之前执行;后置通知是在目标方法执行之后执行,但是目标方法如果有异常,后置通知不在执行;而最终通知无论目标方法有没有异常都会执行;异常通知是捕获异常使用的;环绕通知能控制目标方法的执行。这就是以上的几种通知。小编将配置文件简单化,如果读者想拿代码测试一下的话,可以结合着SpringAop入门将代码补全。
相关文章推荐
- Spring AOP使用整理:各种通知类型的介绍
- 【Spring实战】----解析Spring AOP
- Nginx服务器限制IP访问的各种情况全解析
- 【Oracle学习笔记-3】关于Oracle 10g中各种服务解析
- 【解析】.NET中代理服务器WebProxy的各种用法
- Spring AOP那些学术概念—通知、增强处理连接点(JoinPoint)切面(Aspect)(转)
- spring aop五种通知及通知中传递参数!
- XML--解析xml各种用法区别及用法汇总
- asp.net各种cookie代码和解析
- YUV 各种格式解析(转)
- PHP XML操作的各种方法解析(比较详细)
- SpringAop_各种通知
- 【Android 应用开发】Android屏幕适配解析 - 详解像素,设备独立像素,归一化密度,精确密度及各种资源对应的尺寸密度分辨率适配问题
- spring03 AOP、各种通知、一/多个切面例子
- Android Context完全解析,你所不知道的Context的各种细节
- JavaScript:全面解析各种浏览器网页中的JS代码的执行顺序
- Android Context完全解析,你所不知道的Context的各种细节
- 18Spring_AOP编程(AspectJ)_AspectJ的各种通知总结
- Android屏幕适配解析 - 详解像素,设备独立像素,归一化密度,精确密度及各种资源对应的尺寸密度分辨率适配问题
- ActionBar各种属性的详细解析