
AOP编程
一、AOP核心概念
场景:银行办理业务
AOP的作用:把「排号叫号」这些通用操作从业务代码中抽离出来,实现非侵入式增强
二、5分钟理解AOP术语
术语
切面(Aspect)要添加的通用功能模块
连接点(Join Point)可以插入代码的位置
通知(Advice)具体插入的代码逻辑
切点(Pointcut)定义哪些连接点要插入代码
目标对象(Target)被增强的对象
三、Spring AOP实战:自动记录日志
步骤1:添加依赖
xml
<!-- Spring Boot AOP支持 --> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
java
@Aspect @Component public class LoggingAspect {
// 定义切点:拦截所有Service层方法 @Pointcut("execution(* com.example.service.*.*(..))") public void serviceMethods() {} // 前置通知:方法执行前记录日志 @Before("serviceMethods()") public void logMethodStart(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); System.out.println("【开始执行】" + methodName); } // 后置通知:方法执行后记录日志(即使抛出异常也会执行) @After("serviceMethods()") public void logMethodEnd(JoinPoint joinPoint) { System.out.println("【执行结束】" + joinPoint.getSignature().getName()); } // 环绕通知:统计方法耗时 @Around("serviceMethods()") public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { long start = System.currentTimeMillis(); Object result = joinPoint.proceed(); // 执行原方法 long duration = System.currentTimeMillis() - start; System.out.println("【耗时统计】" + joinPoint.getSignature() + " 执行耗时:" + duration + "ms"); return result; }
}
步骤3:测试效果
java
@Service public class UserService { public void createUser(String name) { System.out.println("创建用户: " + name); } }
// 调用时控制台输出: // 【开始执行】createUser // 创建用户: Alice // 【执行结束】createUser // 【耗时统计】void com.example.service.UserService.createUser(String) 执行耗时:2ms
AOP底层原理
java
public class UserServiceProxy extends UserService { private UserService target; private LoggingAspect aspect;
@Override public void createUser(String name) { aspect.logMethodStart(); // 前置通知 try { target.createUser(name); // 调用原方法 aspect.logMethodEnd(); // 后置通知 } catch (Exception e) { aspect.logException(e); // 异常通知 } }
}