您的位置:首页 > 编程语言 > Java开发

记录方法运行时间——基于spring的面向切面编程简单实例

2017-02-07 20:40 423 查看
工程中有很多方法需要记录方法的运行时间,本质上这是独立于主业务逻辑且复用性很强的功能,类似的还有权限控制,用户验证,打log等。如果每个方法里都要反复去写是一件很low的事情,但是如果改用切面编程来实现就十分清爽了。

spring中用@Aspect可以定义一个切面类,用@Pointcut定义一个切点表达式方法。Pointcut的execution即是用正则表达式定义的包+类+方法组成的切面场景。针对切面场景,有@Before@After@AfterReturning@AfterThrowing@Around等不同的通知去取方法执行不同阶段的各种上下文。

@Component
@Aspect
public class MethodRunTimeInterceptor {

private static final Logger LOGGER = LoggerFactory.getLogger(MethodRunTimeInterceptor.class);
private long startTime = 0;

@Pointcut("execution(public * *.*.*())")
public void recordTime() {
}

@Before("recordTime()")
public void before(JoinPoint jp) {
startTime = System.currentTimeMillis();
}

@AfterReturning("recordTime()")
public void afterReturning(JoinPoint jp) {
long spendTime = System.currentTimeMillis() - startTime;
String className = jp.getTarget().getClass().getSimpleName();
String methodName = jp.getSignature().getName();

LOGGER.info("{} {} costs {}ms ",className,methodName,spendTime);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: