关于如何获取项目中所有API路径问题

@Autowired
WebApplicationContext applicationContext;

private final RequestMappingHandlerMapping requestMappingHandlerMapping;

public TestController(RequestMappingHandlerMapping requestMappingHandlerMapping) {
    this.requestMappingHandlerMapping = requestMappingHandlerMapping;
}

/**
 * 获取项目所有api信息
 */
@GetMapping("/getParam")
public void getParam(){

    RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
    // 拿到Handler适配器中的全部方法
    // 这是第一种,没有获取api注释
    Map<RequestMappingInfo, HandlerMethod> methodMap = mapping.getHandlerMethods();
    Set<String> urlList = new HashSet<>();
    for (RequestMappingInfo info : methodMap.keySet()){

        Set<String> urlSet = info.getPatternsCondition().getPatterns();
        // 请求方式
        Set<RequestMethod> Methods = info.getMethodsCondition().getMethods();
        // 加上自己的域名和端口号,就可以直接用
        urlList.addAll(urlSet);
    }
    for (String url : urlList) {
        // 后端代码中所有api的url
        System.out.println("https://vip.xxxx.com/" + url);
    }
	// 这是第二种,获取api注释
    Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
    for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) {
        HandlerMethod method = entry.getValue();
        Set<String> uriPatterns = entry.getKey().getPatternsCondition().getPatterns();
        Set<RequestMethod> methodPatterns = entry.getKey().getMethodsCondition().getMethods();
        if(CollectionUtil.isEmpty(uriPatterns) || CollectionUtil.isEmpty(methodPatterns)){
            continue;
        }
        String methodPattern =  new ArrayList<String>(uriPatterns).get(0);
        String methodTypePattern =  new ArrayList<RequestMethod>(methodPatterns).get(0).name();
        Annotation[] annotations = method.getMethod().getDeclaredAnnotations();
        if (annotations == null) {
            continue;
        }
        for (Annotation annotation : annotations) {
            //获取所有用了ApiOperation注解的方法类
            if (annotation instanceof ApiOperation) {
                ApiOperation methodDesc = (ApiOperation) annotation;

                //方法描述
                String methodDescName = methodDesc.value();
                //方法名
                String methodName = method.getMethod().getName();
                //类全名
                String classAllName = method.getBeanType().getName();
                // @ApiOperation 中value名称
                System.out.println(methodDescName +"|"+ "https://vip.xxxx.com/" +methodPattern );
            }
        }
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值