Spring Boot 在拦截器中获取 Controller 中的注解

Spring Boot About 1,143 words

需求

HandlerInterceptor拦截器中获取Controller中的注解,判断是否标注了注解,获取注解中的值等。

实现

自定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RateLimiter {

}

标注 Controller

@RequiredArgsConstructor
@RestController
public class LoginController {

    private final LoginService loginService;

    @RateLimiter
    @PostMapping(value = "/login")
    public Credentials login(@RequestBody Identity identity) {
        return loginService.login(identity);
    }

}

获取注解

当在HandlerInterceptor注入在Spring MVC时,他的参数Object handler类型是HandlerMethod

使用HandlerMethod可以获取Controller中的诸多元信息,包括注解、方法名、参数类型等。

@Slf4j
public class RateLimiterInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod hm) {
            if (hm.hasMethodAnnotation(RateLimiter.class)) {
                RateLimiter limiter = hm.getMethodAnnotation(RateLimiter.class);
                // TODO
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

}
Views: 2,203 · Posted: 2023-02-05

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh