xml添加配置
在<aop:config>
中添加配置:
<aop:advisor pointcut-ref="pc" advice-ref="logMethodTimeAdvice" order="1"/>
advice
类书写
这个方法会在配置的类切面执行
invocation.getMethod().
拿到的那个方法就是连接点
package com.gavin.exam.advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import com.gavin.exam.service.impl.UserServiceImpl;
public class LogMethodTimeAdvice implements MethodInterceptor {
private final Logger logger = Logger.getLogger(UserServiceImpl.class);
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
Object returnValue = invocation.proceed(); //方法执行
String methodName = invocation.getMethod().getName();
long endTime = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
sb.append(invocation.getMethod().getDeclaringClass().getSimpleName());
sb.append(":");
sb.append(methodName);
sb.append(" time:");
sb.append(endTime - startTime);
logger.info(sb.toString());
return returnValue;
}
}