在preHandle中需先判断handler是否为HandlerMethod类型,再通过getMethod()获取Method对象读取注解;若需类级注解,则用getBeanType()获取Controller类。

在 preHandle 方法中获取目标处理器方法(即 HandlerMethod)上的注解,关键在于先将 handler 参数安全地强转为 HandlerMethod 类型,再调用其 getMethod() 或 getBeanType() 等方法获取反射对象,进而读取注解。
确认 handler 是 HandlerMethod 类型
preHandle 的第二个参数 handler 类型是 Object,Spring MVC 只有在匹配到控制器方法时才传入 HandlerMethod 实例;静态资源、错误页或自定义 Handler 可能不是该类型,必须先做类型判断:
- 使用
if (handler instanceof HandlerMethod)安全判断 - 若不满足,直接返回
true(放行)或按需处理,避免ClassCastException
从 HandlerMethod 提取 Method 并获取注解
确认类型后,可调用 ((HandlerMethod) handler).getMethod() 获取底层 java.lang.reflect.Method 对象,然后用标准反射 API 读取注解:
-
method.getAnnotation(YourAnnotation.class):获取指定类型的注解实例(单值) -
method.getAnnotations():获取方法上所有注解数组 -
method.isAnnotationPresent(YourAnnotation.class):仅判断是否存在,性能略优
注意 Controller 类上注解的获取方式
如果需要同时检查类级别注解(如 @RequestMapping 在类上),应通过 ((HandlerMethod) handler).getBeanType() 获取控制器类的 Class 对象,再调用 getAnnotation():
立即学习“Java免费学习笔记(深入)”;
Class<?> controllerClass = ((HandlerMethod) handler).getBeanType();controllerClass.getAnnotation(RestController.class)
完整示例代码片段
以下是在 preHandle 中安全获取 @GetMapping 和自定义 @NeedAuth 注解的典型写法:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
// 获取方法上的 @NeedAuth 注解
NeedAuth needAuth = method.getAnnotation(NeedAuth.class);
if (needAuth != null && needAuth.required()) {
// 执行鉴权逻辑
}
// 检查是否是 GET 请求(也可用 @GetMapping 判断)
if (method.isAnnotationPresent(GetMapping.class)) {
// 处理 GET 相关逻辑
}
}
return true;
}


















