博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springboot添加自定义注解
阅读量:4330 次
发布时间:2019-06-06

本文共 2294 字,大约阅读时间需要 7 分钟。

spring拦截器是基于动态代理,注解就是拦截器,所以关于动态代理需要注意的坑,注解同样要注意。

1.创建注解类

/** * @Target 此注解的作用目标,括号里METHOD的意思说明此注解只能加在方法上面,TYPE意思是可注解于类上 * @Retention 注解的保留位置,括号里RUNTIME的意思说明注解可以存在于运行时,可以用于反射 * @Documented 说明该注解将包含在javadoc中 */ @Target(value = {ElementType.METHOD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @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")@Primarypublic class TokenConfiger implements WebMvcConfigurer{    @Bean    IgnoreTokenHandle getIgnoreTokenHandle(){        return new IgnoreTokenHandle();    }    @Override    public void addInterceptors(InterceptorRegistry registry) {        ArrayList
commonPathPatterns = getExcludeCommonPathPatterns(); registry.addInterceptor(getIgnoreTokenHandle()).addPathPatterns("/**").excludePathPatterns(commonPathPatterns.toArray(new String[]{})); } private ArrayList
getExcludeCommonPathPatterns() { ArrayList
list = new ArrayList<>(); String[] urls = { "/v2/api-docs", "/swagger-resources/**", "/cache/**", "/api/log/save" }; Collections.addAll(list, urls); return list; }}

这三部注解就已经可以生效。

完了在你的controller层 类上或方法上加上注解都会生效

转载于:https://www.cnblogs.com/yoishion/p/10737542.html

你可能感兴趣的文章
C6748和音频ADC连接时候的TDM以及I2S格式问题
查看>>
UIView的layoutSubviews,initWithFrame,initWithCoder方法
查看>>
STM32+IAP方案 实现网络升级应用固件
查看>>
用74HC165读8个按键状态
查看>>
jpg转bmp(使用libjpeg)
查看>>
linear-gradient常用实现效果
查看>>
sql语言的一大类 DML 数据的操纵语言
查看>>
VMware黑屏解决方法
查看>>
JS中各种跳转解析
查看>>
JAVA 基础 / 第八课:面向对象 / JAVA类的方法与实例方法
查看>>
Ecust OJ
查看>>
P3384 【模板】树链剖分
查看>>
Thrift源码分析(二)-- 协议和编解码
查看>>
考勤系统之计算工作小时数
查看>>
4.1 分解条件式
查看>>
Equivalent Strings
查看>>
flume handler
查看>>
收藏其他博客园主写的代码,学习加自用。先表示感谢!!!
查看>>
H5 表单标签
查看>>
su 与 su - 区别
查看>>