少年阿宾

那些青春的岁月

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks
package com.cp.common.aop;
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class TimeHandler
  implements MethodInterceptor
{
  private static final Log log = LogFactory.getLog(TimeHandler.class);
  private int error;
  private int warn;
  private int info;
  public TimeHandler()
  {
    this.error = 200;
    this.warn = 100;
    this.info = 50;
  }
  public Object invoke(MethodInvocation methodInvocation)
    throws Throwable
  {
    long procTime = System.currentTimeMillis();
    try {
      Object result = methodInvocation.proceed();
     return result;
    }
    finally {
      procTime = System.currentTimeMillis() - procTime;
      String msg = "Process method " + methodInvocation.getMethod().getName() + " successful! Total time: " + procTime + " milliseconds!";
      if (procTime > this.error)
        if (log.isErrorEnabled()) log.error(msg);
      else if (procTime > this.warn)
        if (log.isWarnEnabled()) log.warn(msg);
      else if (procTime > this.info)
        if (log.isInfoEnabled()) log.info(msg);
      else if (log.isDebugEnabled()) log.debug(msg);
    }
  }
  public void setError(int error)
  {
    this.error = error;
  }
  public void setWarn(int warn)
  {
    this.warn = warn;
  }
  public void setInfo(int info)
  {
    this.info = info;
  }
}
/*
对于上面的代码需要说明的是下面两行代码:
  Object result = methodInvocation.proceed();
  return result;
整个程序的流程是这样的:
  1,先是执行在Object result = methodInvocation.proceed();前面的代码;
  2,接着执行Object result = methodInvocation.proceed();,它把执行控制权交给了interceptor stack(拦截器栈)内的下一个interceptor,如果没有了就交给真正的业务方法;
  3,然后执行return result;之前的代码;
  4,最后执行return result;,它把控制权交回它之上的interceptor,如果没有了就退出interceptor stack。
*/
posted on 2015-02-25 17:36 abin 阅读(407) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: