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配置文件中添加如下
    <bean id="timeInterceptor" class="com.questionnaire.common.filter.TimeInterceptor">
    <property name="error" value="150" />
    </bean>
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
        <property name="beanNames">
            <value>*DAO</value>
        </property>
        <property name="interceptorNames">
            <list>
                <value>timeInterceptor</value>
            </list>
        </property>
    </bean>

你可能感兴趣的:(java,spring,AOP,Interceptor,time)