java写的一个拦截dao层时间的interceptor

阅读更多
1.创建一个文件TimeInterceptor.java代码如下
package com.questionnaire.common.filter;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TimeInterceptor implements MethodInterceptor {

private static final Log log = LogFactory.getLog(TimeInterceptor.class);
private int error;

public TimeInterceptor() {
this.error = 50;
}

@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
long procTime = System.currentTimeMillis();
try {
return methodInvocation.proceed();
} 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);
}
}
}

public void setError(int error) {
this.error = error;
}

}
2.在spring配置文件中添加如下
   
   
   


       
            *DAO
       

       
           
                timeInterceptor
           

       

   

你可能感兴趣的:(java,spring,aop,interceptor,time)