栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

微服务系列之SpringBoot基础:自定义注解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

微服务系列之SpringBoot基础:自定义注解

文章目录

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 {
   //此处省略具体逻辑
 }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/754636.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号