一般写法
long start = System.currentTimeMillis();
try {
// .... 具体的代码段
} finally {
System.out.println("cost: " + (System.currentTimeMillis() - start));
}
aop
// 定义切点,拦截所有满足条件的方法
@Pointcut("execution(public * com.git.hui.boot.aop.demo.*.*(*))")
public void point() {
}
@Around("point()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
try{
return joinPoint.proceed();
} finally {
System.out.println("cost: " + (System.currentTimeMillis() - start));
}
}
jdk1.7后AutoCloseable
// 定义类
public static class Cost implements AutoCloseable {
private long start;
public Cost() {
this.start = System.currentTimeMillis();
}
@Override
public void close() {
System.out.println("cost: " + (System.currentTimeMillis() - start));
}
}
// 使用姿势
try (Cost c = new Cost()) {
...
}