)
Spring知识梳理(6)作者没有四次元口袋的蓝胖日期2026-07-18标签Java, Spring, AOP, 切面注解, Pointcut, 自定义注解一、核心注解一览注解作用标注位置Aspect声明这是一个切面类类上Pointcut定义切入点表达式方法上方法体为空Before前置通知方法上AfterReturning后置通知正常返回方法上Around环绕通知最强大方法上AfterThrowing异常通知方法上After最终通知无论是否异常方法上EnableAspectJAutoProxy开启 AOP 功能配置类上EnableAspectJAutoProxy// 开启 AOPSpring Boot 已默认开启ConfigurationpublicclassAppConfig{}二、Pointcut 表达式详解2.1 execution 表达式格式修饰符? 返回值 类名.方法名(参数) 异常?2.2 常用写法速查// service 包下所有类的所有方法execution(*com.example.service.*.*(..))// service 包及其子包下所有类的所有方法注意 ..execution(*com.example.service..*.*(..))// 指定类的所有方法execution(*com.example.service.UserService.*(..))// 指定类的指定方法execution(*com.example.service.UserService.save(..))// 所有以 save 开头的方法execution(**.save*(..))// 所有 public 方法execution(public**(..))// 所有返回值是 String 的方法execution(String*(..))// 有两个参数的方法execution(**(..,..))// 第一个参数是 String 的方法execution(**(String,..))2.3 注解匹配// 标注了 MyLog 注解的方法annotation(com.example.MyLog)// 标注了 Service 的类中所有方法within(org.springframework.stereotype.Service)// 标注了 Transactional 的方法annotation(org.springframework.transaction.annotation.Transactional)2.4 组合表达式// 同时满足execution(*com.example.service..*.*(..))annotation(com.example.MyLog)// || 满足其一execution(*com.example.service.UserService.*(..))||execution(*com.example.service.OrderService.*(..))// ! 取反!execution(*com.example.service.InternalService.*(..))三、实战日志切面完整示例这是实际开发中最常见的 AOP 应用场景面试也最爱问。3.1 定义自定义注解Target(ElementType.METHOD)Retention(RetentionPolicy.RUNTIME)DocumentedpublicinterfaceMyLog{Stringvalue()default;// 操作描述}3.2 在业务方法上使用ServicepublicclassUserService{MyLog(删除用户)publicvoiddeleteUser(Longid){// 业务逻辑}MyLog(创建用户)publicUsercreateUser(Stringname){// 业务逻辑}}3.3 编写切面AspectComponentpublicclassMyLogAspect{// 定义切入点所有标注 MyLog 的方法Pointcut(annotation(com.example.MyLog))publicvoidlogPointcut(){}// 环绕通知Around(logPointcut())publicObjectaround(ProceedingJoinPointpjp)throwsThrowable{// 获取注解信息MethodSignaturesignature(MethodSignature)pjp.getSignature();Methodmethodsignature.getMethod();MyLogmyLogmethod.getAnnotation(MyLog.class);StringoperationmyLog.value();StringmethodNamesignature.getDeclaringTypeName().signature.getName();Object[]argspjp.getArgs();// 前置日志System.out.println( 操作开始 );System.out.println(操作: operation);System.out.println(方法: methodName);System.out.println(参数: Arrays.toString(args));longstartSystem.currentTimeMillis();try{// 执行目标方法Objectresultpjp.proceed();// 后置日志longcostSystem.currentTimeMillis()-start;System.out.println(耗时: costms);System.out.println(返回: result);System.out.println( 操作完成 );returnresult;}catch(Exceptione){// 异常日志longcostSystem.currentTimeMillis()-start;System.out.println(耗时: costms);System.out.println(异常: e.getMessage());System.out.println( 操作失败 );throwe;// 继续抛出异常}}}3.4 效果userService.deleteUser(1L);// 控制台输出// 操作开始 // 操作: 删除用户// 方法: com.example.service.UserService.deleteUser// 参数: [1]// 耗时: 15ms// 返回: null// 操作完成 这就是实际开发中日志切面的标准写法自定义注解 Around 环绕通知。四、实战权限校验切面// 1. 定义权限注解Target(ElementType.METHOD)Retention(RetentionPolicy.RUNTIME)publicinterfaceRequiresRole{Stringvalue();// 需要的角色}// 2. 业务方法RestControllerpublicclassAdminController{RequiresRole(ADMIN)GetMapping(/admin/users)publicListUserlistUsers(){returnuserService.findAll();}}// 3. 权限切面AspectComponentpublicclassAuthAspect{Around(annotation(requiresRole))publicObjectcheckAuth(ProceedingJoinPointpjp,RequiresRolerequiresRole)throwsThrowable{StringrequiredRolerequiresRole.value();// 获取当前用户角色从 SecurityContext / Token 中获取StringcurrentRolegetCurrentUserRole();if(!requiredRole.equals(currentRole)){thrownewAccessDeniedException(权限不足需要: requiredRole, 当前: currentRole);}// 权限通过执行目标方法returnpjp.proceed();}privateStringgetCurrentUserRole(){// 从 ThreadLocal / SecurityContext / Token 中获取当前用户角色returnSecurityContextHolder.getContext().getAuthentication().getAuthorities().toString();}}五、实战接口限流切面// 1. 定义限流注解Target(ElementType.METHOD)Retention(RetentionPolicy.RUNTIME)publicinterfaceRateLimit{intmaxRequests()default100;// 最大请求数inttimeWindow()default60;// 时间窗口秒}// 2. 限流切面AspectComponentpublicclassRateLimitAspect{// 用 ConcurrentHashMap 记录每个方法的请求次数privatefinalConcurrentHashMapString,AtomicIntegercountersnewConcurrentHashMap();privatefinalConcurrentHashMapString,LongtimestampsnewConcurrentHashMap();Around(annotation(rateLimit))publicObjectlimit(ProceedingJoinPointpjp,RateLimitrateLimit)throwsThrowable{Stringkeypjp.getSignature().toShortString();longnowSystem.currentTimeMillis();longwindowrateLimit.timeWindow()*1000L;// 重置计数器如果超过时间窗口timestamps.compute(key,(k,v)-{if(vnull||now-vwindow){counters.put(key,newAtomicInteger(0));returnnow;}returnv;});intcountcounters.get(key).incrementAndGet();if(countrateLimit.maxRequests()){thrownewRuntimeException(请求过于频繁请稍后再试);}returnpjp.proceed();}}// 3. 使用RestControllerpublicclassApiController{RateLimit(maxRequests10,timeWindow60)// 60秒内最多10次GetMapping(/api/data)publicStringgetData(){returndata;}}六、AOP 典型应用场景总结场景实现方式本质事务管理TransactionalSpring 内置切面自定义注解 Around日志记录自定义MyLogAround自定义注解 Around权限校验自定义RequiresRoleBefore自定义注解 Before接口限流自定义RateLimitAround自定义注解 Around缓存CacheableSpring 内置切面自定义注解 Around性能监控Around记录方法耗时Around统一模式自定义注解 AOP 环绕通知。掌握了这个模式上面所有场景都能实现。七、注意事项与常见坑7.1 同类方法调用 AOP 失效ServicepublicclassUserService{publicvoidmethodA(){this.methodB();// ⚠️ 这里调用 methodBAOP 不会生效}MyLog(方法B)publicvoidmethodB(){// ...}}原因this.methodB()是目标对象内部调用不经过代理对象所以 AOP 无法拦截。解决// 方案一注入自身代理AutowiredprivateUserServiceself;publicvoidmethodA(){self.methodB();// 通过代理调用AOP 生效}// 方案二从 AopContext 获取代理publicvoidmethodA(){UserServiceproxy(UserService)AopContext.currentProxy();proxy.methodB();}7.2 private 方法 AOP 失效MyLog(私有方法)privatevoidprivateMethod(){...}// AOP 无法拦截 private 方法原因无论是 JDK 代理还是 CGLIB都无法代理 private 方法。7.3 Transactional 也是 AOPTransactional本质上就是一个 Spring 内置的切面用Around包裹方法执行在方法前开启事务正常返回时提交抛异常时回滚。八、思维导图速览切面注解实战 ├── 核心注解 │ ├── Aspect声明切面 │ ├── Pointcut定义切入点 │ ├── Before / After / Around / AfterReturning / AfterThrowing │ └── EnableAspectJAutoProxy开启 AOP │ ├── Pointcut 表达式 │ ├── execution() 匹配方法签名 │ ├── annotation() 匹配注解 │ ├── within() 匹配类注解 │ └── / || / ! 组合使用 │ ├── 典型应用统一模式自定义注解 Around │ ├── Transactional 事务 │ ├── MyLog 日志记录 │ ├── RequiresRole 权限校验 │ ├── RateLimit 接口限流 │ └── Cacheable 缓存 │ └── 常见坑 ├── 同类内部方法调用 → AOP 失效this 调用不经过代理 ├── private 方法 → 无法代理 └── final 类/方法 → CGLIB 无法代理九、写在最后面试回答模板“实际开发中 AOP 最常用的模式是自定义注解 环绕通知。比如日志切面定义一个 MyLog 注解切面类用 Pointcut 匹配标注了该注解的方法在 Around 中记录方法名、参数、耗时、返回值。权限校验、接口限流、缓存都是同样的套路。Transactional本质上也是 Spring 内置的切面。要注意同类内部方法调用会导致 AOP 失效因为this调用不经过代理对象。”学习建议重点掌握自定义注解 Around的完整套路面试最爱问Pointcut 表达式记住execution()和annotation()两种最常用的常见坑同类调用失效、private 方法失效面试可能追问建议动手写一个日志切面跑通了就全懂了