springboot添加自定义注解

Spring注解拦截器实战
本文详细介绍如何在Spring框架中使用注解实现拦截器功能,包括注解的创建、拦截器的定义及配置过程,最后演示如何在Controller层应用注解以实现特定请求的拦截。

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层 类上或方法上加上注解都会生效

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值