Step1、定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MySecured {
    String value() default "";
}

Step2、定义拦截器

public class MySecuredInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod=(HandlerMethod) handler;
        Method method=handlerMethod.getMethod();
        MySecured mySecured=method.getAnnotation(MySecured.class);
        if(mySecured!=null){
            String value=mySecured.value();
            if("tom".equals(value)){
                return true;
            }
            return false;
        }
        return false;
    }
}

Step3、注册拦截器

@Configuration
public class MyWebConfiger extends WebMvcConfigurationSupport {
    @Resource
    private MySecuredInterceptor mySecuredInterceptor;

    @Bean
    public MySecuredInterceptor mySecuredInterceptor(){
        return new MySecuredInterceptor();
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(mySecuredInterceptor);
    }
}

Step4、使用注解

@RestController
public class DemoController {
    @GetMapping("/getValue")
    @MySecured("tom")
    public String getValue(){
        return "hello world";
    }
}

注:SpringBoot 拦截器

拦截器是SpringMVC中的组件,由接口HandlerInterceptor定义,该接口由3个方法,分别对应前置、后置和请求完成后调用。通过实现该接口即可实现一个拦截器;只需要其中个别方法时,继承HandlerInterceptorAdapter并重写对应的方法即可。

如下图所示,SpringMVC拦截器作用于Controller层。 图片说明