使用@Pointcut("@annotation(全限定类名)")可精准拦截加注解方法,需确保注解声明含@Target和@Retention(RetentionPolicy.RUNTIME),切点表达式用全限定名,切面类加@Component和@Aspect,通知引用切点方法名。
直接用 @Pointcut("@annotation(全限定类名)) 就能精准拦截加了该注解的方法,关键在注解声明、切面写法和包路径三处不能出错。
自定义注解必须声明作用范围和生命周期,否则 AOP 无法识别:
ElementType.TYPE)示例:
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface Log { String value() default "";}
使用 @annotation 切点时,括号里填的是注解的全限定类名(含包路径),不是简单类名:
立即学习“Java免费学习笔记(深入)”;
@Pointcut("@annotation(cn.zhy.annotation.Log)")
@Pointcut("@annotation(Log)") 或 @Pointcut("@annotation(log)")
这个表达式只会匹配被 @Log 显式标注的方法,不关心所在类是否是 Controller 或 Service。
切面类本身要被 Spring 管理,且通知方法引用切点方法名(不是表达式字符串):
@Component 和 @Aspect 注解@Pointcut 方法建议用 private,只作表达式载体,不执行逻辑@Before)中直接写 "pointcutMethod()",不要重复写表达式示例:
@Component@Aspectpublic class LogAspect { @Pointcut("@annotation(cn.zhy.annotation.Log)") private void logPointcut() {} @Before("logPointcut()") public void doBefore(JoinPoint joinPoint) { System.out.println("方法 " + joinPoint.getSignature().getName() + " 开始执行"); }}
只要方法上有 @Log,无论它在 Controller、Service 还是 Utils 类里,都会被拦截:
@RestControllerpublic class UserController { @Log("用户查询操作") @GetMapping("/user/{id}") public User getById(@PathVariable Long id) { return userService.findById(id); }}
启动应用后调用该接口,控制台就会打印前置日志——无需改方法签名、不侵入业务代码。