获取Controller层接口信息,并组装,返回前端


前言

提示:这里可以添加本文要记录的大概内容:

获取Controller层接口信息,并组装,返回前端
描述信息组装在swagger中:
在Controller层中的方法上添加如下注解:
@ApiOperation(value = “获取所有api资源”)
淡然也能自定义注解


一、Controller层

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@Api(tags="菜单相关操作")
@Slf4j
@RestController
@RequestMapping(value = "/menu")
public class MenuController  extends BaseController{

    @Autowired
    private MenuService menuService;

// contriller 层中每个方法都需要添加该注解:value为其描述,该注解为swagger注解
    @ApiOperation(value = "获取所有api资源")
    @GetMapping(value = "/api")
    public ResponseData<Map<String, List<ApiUrlInfo>>> getAllApi(){
        Map<String, List<ApiUrlInfo>> result = menuService.getAllApi();
        return ResponseData.success(result);
    }
}

二、Service层

public interface MenuService {
    /**
     * 获取所有用户api信息
     * @return
     */
    Map<String, List<ApiUrlInfo>> getAllApi();

}

三、ServiceImpl层

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.*;

@Slf4j
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    /**
     * 添加缓存:
     */
    private final Map<String,List<ApiUrlInfo>> result = new HashMap<>();

    @Override
    public Map<String, List<ApiUrlInfo>> getAllApi() {
    // 获取所有接口信息
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();

        if (result.size()!=0){
            return result;
        }
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            RequestMappingInfo rmi = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();
            Method method = handlerMethod.getMethod();
            ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
            ApiUrlInfo endpointInfo = new ApiUrlInfo();
            endpointInfo.setApiUrl(rmi.getPatternsCondition().toString());
            endpointInfo.setRequestMethods(rmi.getMethodsCondition().toString());
            endpointInfo.setController(handlerMethod.getBeanType().getName());
            endpointInfo.setMethod(handlerMethod.getMethod().getName());
            if (apiOperation != null) {
                endpointInfo.setDescription(apiOperation.value());
            }
            List<ApiUrlInfo> endpointInfos = result.get(handlerMethod.getBeanType().getName());
            if (CollectionUtils.isNotEmpty(endpointInfos)){
                endpointInfos.add(endpointInfo);
                result.put(handlerMethod.getBeanType().getName(),endpointInfos);
            }else {
                List<ApiUrlInfo> endpoints = new ArrayList<>();
                endpoints.add(endpointInfo);
                result.put(handlerMethod.getBeanType().getName(),endpoints);
            }
        }
        log.info("获取最终数据为:",JSON.toJSONString(result));
        return result;
    }
}

四、dao层


@Data
public class ApiUrlInfo {

    @ApiModelProperty(value = "URL")
    private String apiUrl;

    @ApiModelProperty(value = "请求的 HTTP 方法")
    private String requestMethods;

    @ApiModelProperty(value = "控制器名称")
    private String controller;

    @ApiModelProperty(value = "方法名称")
    private String method;

    @ApiModelProperty(value = "API 操作的描述")
    private String description;
}
}

五、项目启动加载:(需要则配置)


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Map;

/**
 * @program: 
 * @description: 获取Controller层接口api
 **/
@Component
public class EndpointDocumenter  implements CommandLineRunner {

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    @Override
    public void run(String... args) {
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            RequestMappingInfo rmi = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();

            System.out.println("URL Patterns: " + rmi.getPatternsCondition());
            System.out.println("Request Methods: " + getRequestMethods(rmi));
            System.out.println("Controller: " + handlerMethod.getBeanType().getName());
            System.out.println("Method: " + handlerMethod.getMethod().getName());
            System.out.println("---------------------------------");
        }
    }

    private String getRequestMethods(RequestMappingInfo rmi) {
        StringBuilder sb = new StringBuilder();
        for (RequestMethod method : rmi.getMethodsCondition().getMethods()) {
            sb.append(method).append(", ");
        }
        if (sb.length() > 0) {
            sb.setLength(sb.length() - 2); // Remove trailing comma and space
        }
        return sb.toString();
    }
}



总结

线上慎用,推测其可能swagger底层使用的也是该原理

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值