spring拦截器是基于动态代理,注解就是拦截器,所以关于动态代理需要注意的坑,注解同样要注意。
1.创建注解类
/** * @Target 此注解的作用目标,括号里METHOD的意思说明此注解只能加在方法上面,TYPE意思是可注解于类上 * @Retention 注解的保留位置,括号里RUNTIME的意思说明注解可以存在于运行时,可以用于反射 * @Documented 说明该注解将包含在javadoc中 */ @Target(value = {ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface IgnoreToken{ }
2.定义拦截器
public class IgnoreTokenHandle extends HandlerInterceptorAdapter{ /** * This implementation always returns {@code true}. */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HandlerMethod handlerMethod = (HandlerMethod) handler; IgnoreToken ignore = handlerMethod.getBeanType().getAnnotation(IgnoreToken.class); //Ver ver = handlerMethod.getBeanType().getAnnotation(Ver.class); //定义多个注解 if (null == ignore) { ignore = handlerMethod.getMethodAnnotation(IgnoreToken.class);//这里可以正确获取到加在方法上的注解 } if (null == ver) { ver = handlerMethod.getMethod().getDeclaringClass() .getAnnotation(Ver.class);//这里不知道哪个大神写的代码,发现不能获取加在方法上的注解,坑了我半天 } if (ignore != null){ System.out.println("**************************"); } return true; } }
这里踩到了坑。见注释
3.配置拦截地址
@Configuration("admimWebConfig")
@Primary
public class TokenConfiger implements WebMvcConfigurer{
@Bean
IgnoreTokenHandle getIgnoreTokenHandle(){
return new IgnoreTokenHandle();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
ArrayList<String> commonPathPatterns = getExcludeCommonPathPatterns();
registry.addInterceptor(getIgnoreTokenHandle()).addPathPatterns("/**").excludePathPatterns(commonPathPatterns.toArray(new String[]{}));
}
private ArrayList<String> getExcludeCommonPathPatterns() {
ArrayList<String> list = new ArrayList<>();
String[] urls = {
"/v2/api-docs",
"/swagger-resources/**",
"/cache/**",
"/api/log/save"
};
Collections.addAll(list, urls);
return list;
}
}
这三部注解就已经可以生效。
完了在你的controller层 类上或方法上加上注解都会生效
浙公网安备 33010602011771号