前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Spring实战】—— 9 AOP环绕通知

【Spring实战】—— 9 AOP环绕通知

作者头像
用户1154259
发布2018-01-18 14:53:13
5680
发布2018-01-18 14:53:13
举报

假如有这么一个场景,需要统计某个方法执行的时间,如何做呢?   典型的会想到在方法执行前记录时间,方法执行后再次记录,得出运行的时间。 如果采用Spring的AOP,仅仅使用前置和后置方法是无法做到的,因为他们无法共享变量。这样通过环绕通知,就可以快捷的实现。

  首先在切面通知类中声明环绕通知类:

代码语言:javascript
复制
    public void watchPerformance(ProceedingJoinPoint joinpoint){
        try{
            System.out.println("begin!");
            long start = System.currentTimeMillis();
            
            joinpoint.proceed();
            
            long end = System.currentTimeMillis();
            System.out.println("end!        performance took "+(end-start)+" milliseconds");
        }catch(Throwable e){
            System.out.println("eee!We want our money back!");
        }
    }

  在bean.xml配置文件中配置aop:around,锁定方法:

代码语言:javascript
复制
<aop:around pointcut-ref="performance" method="watchPerformance"/>

  这样执行的结果如下:

代码语言:javascript
复制
The audience is taking their seats.
The audience is turning off their cellphones
begin!
Instrumentalist age:25
Playing Jingle Bells:TOOT TOOT TOOT
CLAP CLAP CLAP
end!        performance took 95 milliseconds

  因此可以看出AOP执行的过程如下:

代码语言:javascript
复制
  before()
  around()
  执行方法()
  after/throw()
  around()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-02-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档