SpringBoot自定义注解一、在POM文件中添加aop依赖二、创建注解类三、创建拦截器四、自定义注解使用
SpringBoot自定义注解 一、在POM文件中添加aop依赖二、创建注解类org.springframework.boot spring-boot-starter-aop
@Target(value = ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
@documented
public @interface ValidateApiNotAuth {
}
三、创建拦截器
在拦截器中判断若使用了@ValidateApiNotAuth注解的方法,则不作权限校验。
@Slf4j
public class WebInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
String uri = httpServletRequest.getRequestURI();
String appkey = httpServletRequest.getHeader(C.API_HEADER_PARAM_APPKEY);
String timestamp = httpServletRequest.getHeader(C.API_HEADER_PARAM_TIMESTAMP);
String sign = httpServletRequest.getHeader(C.API_HEADER_PARAM_SIGN);
//标识 不需检查 的注解
if (handler instanceof HandlerMethod) {
HandlerMethod h = (HandlerMethod) handler;
ValidateApiNotAuth methodAnnotation = h.getMethodAnnotation(ValidateApiNotAuth.class);
if (methodAnnotation != null)
return true;
}
//此处省略其它逻辑
return false;
}
}
@Configuration
public class WebAppConfig implements WebMvcConfigurer{
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 配置请求拦截器
registry.addInterceptor(new WebInterceptor()).addPathPatterns("/api/**");
}
}
四、自定义注解使用
在不需要做权限校验的方法上添加@ValidateApiNotAuth注解。
@PostMapping("/uploadVideo")
@ApiOperation(value = "视频文件上传", notes = "上传视频文件至服务器", httpMethod = "POST")
@ValidateApiNotAuth
public void uploadVideo(
@ApiParam(required = true, value = "视频文件") @RequestParam(required = true) MultipartFile file
) throws IOException {
//此处省略具体逻辑
}



