SpringBoot 注解+拦截器

286 阅读1分钟

以下是我在学习 SpringBoot 拦截器时的一些记录,供本人与小伙伴们一起参考学习,有不对的地方请指正。

  • 自定义注解实现
@Target({ElementType.METHOD})  // 注解用于方法上
@Retention(RetentionPolicy.RUNTIME) // 注解在运行期间也存在
public @interface MyAnnotation {}
  • 自定义拦截器
public class MyInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
        if(annotation != null) {
            // 进行相应处理
        }
        return true;
    }
}
  • 配置
@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {
    @Bean
    public MyInterceptor myInterceptor() {
        return new MyInterceptor();
    }
    /**
     * 添加拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}