SpringBoot自定义注解实现拦截器通过

自定义注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DisableAuthentication {
}

拦截器实现判断是否注解标注方法并放行

@Component
public class ClientAuthenticationInterceptor implements HandlerInterceptor {
   @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //OPTIONS请求通过
        if (OPTIONS.equals(request.getMethod())) {
            return true;
        }
        // 如果不是方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //HandlerMethod它不是一个接口,也不是个抽象类,且还是public的。HandlerMethod封装了很多属性,在访问请求方法的时候可以方便的访问到方法、方法参数、方法上的注解、所属类等并且对方法参数封装处理,也可以方便的访问到方法参数的注解等信息。
        Method method = ((HandlerMethod)handler).getMethod();
        //检查跳过是否有认证注解,如果有通过
        if (method.isAnnotationPresent(DisableAuthentication.class)) {
            return true;
        }
        return false;
}
posted @ 2022-02-18 17:28  LuanShiLiuNian  阅读(202)  评论(0编辑  收藏  举报