在做接口统计以及权限设计的时候,都需要获取所有接口的列表
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;
}