前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Spring - 获取所有请求方法

Spring - 获取所有请求方法

作者头像
十毛
发布2021-02-02 15:44:17
发布2021-02-02 15:44:17
2.5K00
代码可运行
举报
运行总次数:0
代码可运行

在做接口统计以及权限设计的时候,都需要获取所有接口的列表

Spring MVC/Spring Boot在启动后会把URL到Handler的映射保存在org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.MappingRegistry#mappingLookup。可以通过RequestMappingHandlerMapping拿到映射后,输出到返回值,也可以写入到Redis里面,方便后续进行访问次数统计,删除不再使用的方法

  • 示例代码
代码语言:javascript
代码运行次数:0
复制
@Autowired
private WebApplicationContext applicationContext;

@RequestMapping(value = {"v1/getAllUrl", "getAllUrl2"})
public Object getAllUrl() {
    RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
    // 获取url与类和方法的对应信息

    List<HttpApiInfo> apiInfoList = Lists.newArrayList();
    for (Map.Entry<RequestMappingInfo, HandlerMethod> m : mapping.getHandlerMethods().entrySet()) {
        RequestMappingInfo info = m.getKey();
        HandlerMethod method = m.getValue();
        RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();

        HttpApiInfo apiInfo = HttpApiInfo.builder()
                .requestMethods(methodsCondition.getMethods())
                .className(method.getMethod().getDeclaringClass().getName())
                .classMethod(method.getMethod().getName())
                .httpUrls(info.getPatternsCondition().getPatterns())
                .build();
        apiInfoList.add(apiInfo);
    }

    return apiInfoList;
}

参考

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 参考
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档