目录
一、AOP简介
AOP(Aspect-Oriented Programming) 面向切面编程,是一种编程范式,通过预编译和运行期间动态代理实现程序功能统一维护的一种技术。下面通过一个简单的案例来了解下AOP如何使用。
1.1 AOP入门案例
假如有这么一个需求,需要你来统计方法的执行时长,这也是性能检测的常用手段。如果不使用 AOP 的话,你大概率会这样做。
public void methodA() {
long startTime = System.currentTimeMillis();
// 业务代码
long endTime = System.currentTimeMillis();
// 计算代码执行时长 endTime - startTime
}
这样做当然没有错,但是如果有很多方法需要你去统计呢,每个方法内都需要有相同的代码,看起来很麻烦。AOP 出现后在很大程度上缓解了这种臃肿的代码,只需要一个注解就可以搞定。
首先需要添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
// 统计方法执行时长的注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExecutionTimeStatistic {
}
@Slf4j
@Aspect
@Component
public class ExecutionTimeAspect {
@Pointcut("@annotation(com.***.ExecutionTimeStatistic)")
public void pointCut() {
}
@Around("pointCut()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object obj = null;
try {
ExecutionTimeStatistic executionTime = getExecutionTime(joinPoint);
if (Objects.isNull(executionTime)) {
return joinPoint.proceed();
}
// 获取方法名
String methodName = joinPoint.getSignature().getName();
// 获取类名
String className = joinPoint.getSignature().getDeclaringTypeName();
StopWatch stopWatch = new StopWatch("methodName");
stopWatch.start();
obj = joinPoint.proceed();
stopWatch.stop();
log.info("执行方法耗时统计, 执行方法为:{}#{}, 耗时:{}", className, methodName, stopWatch.getTotalTimeMillis() + "ms");
} catch (Throwable throwable) {
log.warn("统计方法执行耗时异常", throwable);
throw throwable;
}
return obj;
}
private static ExecutionTimeStat