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 = BeanType().getAnnotation(IgnoreToken.class);
//Ver ver = BeanType().getAnnotation(Ver.class); //定义多个注解
if (null == ignore) {
ignore = MethodAnnotation(IgnoreToken.class);//这⾥可以正确获取到加在⽅法上的注解
}
if (null == ver) {
ver = Method().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("/**").Array(new String[]{}));    }
private ArrayList<String> getExcludeCommonPathPatterns() {
ArrayList<String> list = new ArrayList<>();
String[] urls = {
"/v2/api-docs",
"/swagger-resources/**",
"/cache/**",
spring是什么意思啊"/api/log/save"
};
Collections.addAll(list, urls);
return list;
}
}
这三部注解就已经可以⽣效。
完了在你的controller层类上或⽅法上加上注解都会⽣效

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。