springboot添加自定義注解


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層 類上或方法上加上注解都會生效


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM