工程中有很多方法需要记录方法的运行时间,本质上这是独立于主业务逻辑且复用性很强的功能,类似的还有权限控制,用户验证,打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);
}
}
本文介绍如何使用Spring AOP中的@Aspect注解定义切面类,通过@Pointcut定义切点表达式来记录方法运行时间,提高代码复用性。展示了具体的代码实现细节。
1872

被折叠的 条评论
为什么被折叠?



