spring aop通过@aspect定义切面类,配合@before、@after等通知在不修改业务代码前提下织入横切逻辑;需满足@component和@aspect双标注,切入点表达式决定通知生效位置。

在 Spring AOP 中,用 @Aspect 定义切面类,配合 @Before、@After 等通知注解,就能在不修改业务代码的前提下织入横切逻辑(比如日志、权限、监控)。关键不是堆砌注解,而是理解通知执行时机和切入点表达式怎么写。
定义切面类并启用 AOP
Spring Boot 项目默认已引入 spring-boot-starter-aop,无需额外依赖。普通 Spring 项目需确保添加了 AOP 依赖和 @EnableAspectJAutoProxy 启用代理。
自定义切面类需满足两个条件:
- 被
@Component(或@Service等)标记,让 Spring 扫描到; - 加上
@Aspect注解,表明这是一个切面类。
示例:
@Component
@Aspect
public class LoggingAspect {
// 具体通知方法写在这里
}用 @Before 在目标方法执行前增强
@Before 在目标方法**调用前**执行,适合做参数校验、日志记录、权限预检查等。它不能阻止方法执行(除非抛异常),也不能访问方法返回值。
必须指定切入点表达式(pointcut),常用写法有:
-
@Before("execution(* com.example.service.UserService.*(..))"):匹配UserService类中所有 public 方法; -
@Before("@annotation(org.springframework.web.bind.annotation.PostMapping)"):匹配所有标注了@PostMapping的方法; -
@Before("execution(* com.example.service..*.*(..))"):匹配service包及其子包下所有类的所有方法。
可选地,通过 JoinPoint 获取上下文信息:
@Before("execution(* com.example.service.UserService.findById(..))")
public void logBeforeFindById(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("即将执行方法:" + methodName + ",参数:" + Arrays.toString(args));
}用 @After 在目标方法执行后增强(无论成功或异常)
@After 在目标方法**执行结束后**运行,不管方法是否抛出异常都会触发,类似 finally 块。适合做资源清理、统一收尾、审计日志等。
注意:@After 无法获取方法返回值或异常对象;若需要这些,应改用 @AfterReturning 或 @AfterThrowing。
示例:
@After("execution(* com.example.service.UserService.update*(..))")
public void logAfterUpdate(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("方法 " + methodName + " 已执行完毕(可能成功,也可能失败)");
}组合使用与注意事项
同一个切点可以绑定多个通知,执行顺序由通知类型决定:@Before → 目标方法 → @After → @AfterReturning(成功时)或 @AfterThrowing(异常时)。
常见易错点:
- 切面类没加
@Component,Spring 不会实例化它; - 切入点表达式写错(如包名拼错、缺少
..或*),导致通知不生效; - 对非 Spring 管理的对象(如 new 出来的实例)调用方法,AOP 不起作用(因为没走代理);
- 同一个类内方法相互调用(如 A.method1() 调用 A.method2()),method2() 上的切面不会触发(内部调用绕过代理)。
调试建议:开启 AOP 调试日志,在 application.properties 中添加:logging.level.org.springframework.aop=DEBUG
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











