美文网首页
Spring - 获取所有请求方法

Spring - 获取所有请求方法

作者: 十毛tenmao | 来源:发表于2021-01-28 23:59 被阅读0次

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

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

  • 示例代码
@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;
}

参考

相关文章

网友评论

      本文标题:Spring - 获取所有请求方法

      本文链接:https://www.haomeiwen.com/subject/rpuftltx.html