最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Java中 Spring Pointcut annotation 怎么配置方法级别的自定义注解切点
时间:2026-07-27 08:10:54 编辑:袖梨 来源:一聚教程网
使用@Pointcut("@annotation(全限定类名)")可精准拦截加注解方法,需确保注解声明含@Target和@Retention(RetentionPolicy.RUNTIME),切点表达式用全限定名,切面类加@Component和@Aspect,通知引用切点方法名。
直接用 @Pointcut("@annotation(全限定类名)) 就能精准拦截加了该注解的方法,关键在注解声明、切面写法和包路径三处不能出错。
注解定义要带正确元注解
自定义注解必须声明作用范围和生命周期,否则 AOP 无法识别:
-
@Target(ElementType.METHOD):限定只能标注在方法上(若想支持类级别,加
ElementType.TYPE) - @Retention(RetentionPolicy.RUNTIME):必须是运行时保留,Spring AOP 在运行期靠反射读取
- @Documented(可选):方便生成 JavaDoc;@Inherited(一般不用):注解不继承,AOP 不依赖它
示例:
@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); }}
启动应用后调用该接口,控制台就会打印前置日志——无需改方法签名、不侵入业务代码。