🔪 AOP 切面编程
📊 实时性能统计
AOP 自动统计所有 Controller 和 Service 方法的执行时间
点击按钮查看...
📚 AOP 核心概念
1. 什么是 AOP?
AOP (Aspect-Oriented Programming) 面向切面编程,是将横切关注点与业务逻辑分离的编程范式。
横切关注点:日志、事务、安全、性能监控等,散布在多个模块中的公共功能。
2. 核心术语
| 术语 | 说明 |
| Aspect (切面) | 横切关注点的模块化封装 |
| JoinPoint (连接点) | 程序执行的某个点(方法调用、异常抛出等) |
| Pointcut (切入点) | 匹配连接点的表达式 |
| Advice (通知) | 在连接点执行的动作 |
| Weaving (织入) | 将切面应用到目标对象的过程 |
3. 五种通知类型
| 注解 | 执行时机 | 用途 |
@Before | 方法执行前 | 参数校验、权限检查 |
@After | 方法执行后(无论成功或异常) | 资源清理 |
@AfterReturning | 方法成功返回后 | 结果处理、日志记录 |
@AfterThrowing | 方法抛出异常后 | 异常处理、错误日志 |
@Around | 环绕方法执行(最强大) | 性能统计、事务管理 |
💻 代码示例
日志切面示例
@Aspect
@Component
public class LoggingAspect {
// 切入点:匹配所有 Controller 方法
@Pointcut("execution(* com.example.demo.controller.*.*(..))")
public void controllerMethods() {}
// 前置通知
@Before("controllerMethods()")
public void logBefore(JoinPoint jp) {
System.out.println("[AOP-Before] 方法开始: " + jp.getSignature().getName());
}
// 返回通知
@AfterReturning(pointcut = "controllerMethods()", returning = "result")
public void logAfterReturning(JoinPoint jp, Object result) {
System.out.println("[AOP-AfterReturning] 返回值: " + result);
}
}
性能监控切面 (@Around)
@Aspect
@Component
public class PerformanceAspect {
@Around("execution(* com.example.demo..*.*(..))")
public Object measureTime(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
try {
Object result = pjp.proceed(); // 执行目标方法
long duration = System.currentTimeMillis() - start;
System.out.println("[AOP] " + pjp.getSignature() + " 耗时: " + duration + "ms");
return result;
} catch (Throwable e) {
System.out.println("[AOP] 方法异常: " + e.getMessage());
throw e;
}
}
}
切入点表达式语法
// 匹配任意公共方法
execution(public * *(..))
// 匹配 com.example 包下所有方法
execution(* com.example.*.*(..))
// 匹配 Controller 层所有方法
execution(* com.example.demo.controller.*.*(..))
// 匹配所有 Service 层的 save 开头的方法
execution(* com.example.demo.service.*.save*(..))
// 匹配带有 @Service 注解的类
@within(org.springframework.stereotype.Service)
// 匹配带有自定义注解的方法
@annotation(com.example.demo.aop.RateLimited)
🎯 实际应用场景
| 场景 | 实现方式 |
| 日志记录 | @Before + @AfterReturning |
| 性能监控 | @Around |
| 事务管理 | @Around (Spring 已内置) |
| 权限检查 | @Before |
| 限流控制 | @Around + 自定义注解 |
| 缓存 | @Around (Spring Cache) |
← 返回学习中心