获取Swagger2扫描Controller里面的所有接口

@Component
public class DataInitializer implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(DataInitializer.class);
    private final WebApplicationContext applicationContext;

    public DataInitializer(WebApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(String... args) throws Exception {
        interfaceDataInit();
    }

    public void interfaceDataInit(){
        List<Map<String, String>> allUrl = getAllUrl();
        AirInterfaceMapper airInterfaceMapper = DbMapperPackage.getInstance().getAirInterfaceMapper();
        for (Map<String, String> map : allUrl) {
            AirInterface airInterface = BeanUtil.<AirInterface>mapToBean(map, AirInterface.class, new CopyOptions());
            AirInterface findOne = airInterfaceMapper.selectOne(Wrappers.<AirInterface>lambdaQuery().eq(AirInterface::getMethodUrl, airInterface.getMethodUrl()));
            if (Objects.nonNull(findOne)){
                airInterfaceMapper.update(airInterface, Wrappers.<AirInterface>lambdaQuery().eq(AirInterface::getMethodUrl, airInterface.getMethodUrl()));
            }else {
                airInterfaceMapper.insert(airInterface);
            }
        }
    }

    public List<Map<String, String>> getAllUrl(){
        List<Map<String, String>> resultList = new ArrayList<>();

        RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();

        for (Map.Entry<RequestMappingInfo, HandlerMethod> mappingInfoHandlerMethodEntry : map.entrySet()) {
            Map<String, String> resultMap = new LinkedHashMap<>();

            RequestMappingInfo requestMappingInfo = mappingInfoHandlerMethodEntry.getKey();
            HandlerMethod handlerMethod = mappingInfoHandlerMethodEntry.getValue();

            resultMap.put("className",handlerMethod.getMethod().getDeclaringClass().getName()); // 类名
            Annotation[] parentAnnotations = handlerMethod.getBeanType().getAnnotations();
            for (Annotation annotation : parentAnnotations) {
                if (annotation instanceof Api) {
                    Api api = (Api) annotation;
                    resultMap.put("classDesc",api.value());
                } else if (annotation instanceof RequestMapping) {
                    RequestMapping requestMapping = (RequestMapping) annotation;
                    if (null != requestMapping.value() && requestMapping.value().length > 0) {
                        resultMap.put("classUrl",requestMapping.value()[0]);//类URL
                    }
                }
            }
            resultMap.put("methodName", handlerMethod.getMethod().getName());// 方法名
            Map<String, String> classMap = new HashMap<>();
            Set<Class<?>> processedTypes = new HashSet<>();
            Map<Class<?>, Map<String, Object>> cache = new HashMap<>();
            for (MethodParameter methodParameter : handlerMethod.getMethodParameters()) {
                Class<?> parameterType = methodParameter.getParameterType();
                Parameter parameter = methodParameter.getParameter();
                String name = parameter.getName();
                if (!parameterType.equals(HttpHeaders.class)){
                    if (!parameterType.equals(Integer.class) && !parameterType.equals(String.class)){
                        Map<String, Object> fields = new HashMap<>();
                        processFieldType(parameterType, fields, processedTypes, cache);
                        classMap.put(name, fields.toString());
                    }else {
                        classMap.put(name, parameterType.toString());
                    }
                }
            }
            resultMap.put("methodParams", JSON.toJSONString(classMap));
            Annotation[] annotations = handlerMethod.getMethod().getDeclaredAnnotations();
            if (annotations != null) {
                // 处理具体的方法信息
                for (Annotation annotation : annotations) {
                    if (annotation instanceof ApiOperation) {
                        ApiOperation methodDesc = (ApiOperation) annotation;
                        String desc = methodDesc.notes();
                        resultMap.put("methodDesc",desc);//接口描述
                    }
                }
            }
            PatternsRequestCondition p = requestMappingInfo.getPatternsCondition();
            for (String url : p.getPatterns()) {
                resultMap.put("methodUrl",url);//请求URL
            }
            RequestMethodsRequestCondition methodsCondition = requestMappingInfo.getMethodsCondition();
            for (RequestMethod requestMethod : methodsCondition.getMethods()) {
                resultMap.put("requestType",requestMethod.toString());//请求方式:POST/PUT/GET/DELETE
            }
            resultList.add(resultMap);
        }
        List<Map<String, String>> filterResult = resultList.stream().filter(result -> !result.get("classUrl").equals("/swagger-resources") && !result.get("methodUrl").equals("/error")).collect(Collectors.toList());
        return filterResult;
    }

    private  void processFieldType(Class<?> fieldType, Map<String, Object> fieldMap, Set<Class<?>> processedTypes, Map<Class<?>, Map<String, Object>> cache) {
        if (processedTypes.contains(fieldType)) {
            Map<String, Object> cachedFieldMap = cache.get(fieldType);
            if (!CollectionUtils.isEmpty(cachedFieldMap)){
                fieldMap.putAll(cachedFieldMap);
            }
            return; // 避免重复处理同一类型
        }
        processedTypes.add(fieldType);

        for (Field field : fieldType.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Class<?> type = field.getType();

            if (field.getDeclaringClass().equals(fieldType) && Modifier.isPrivate(field.getModifiers())) {
                if (!type.equals(Integer.class) && !type.equals(String.class) && !type.equals(Date.class)) {
                    Map<String, Object> nestedFieldMap = new HashMap<>();
                    processFieldType(type, nestedFieldMap, processedTypes, cache); // 递归处理字段类型
                    fieldMap.put(fieldName, nestedFieldMap);
                } else {
                    fieldMap.put(fieldName, type);
                }
            }
        }
        cache.put(fieldType, new HashMap<>(fieldMap));
    }
}

插入的表字段

CREATE TABLE `air_interface` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增id',
  `class_name` varchar(255) DEFAULT NULL COMMENT '控制器名称',
  `class_url` varchar(255) DEFAULT NULL COMMENT '控制器路由',
  `method_name` varchar(255) DEFAULT NULL COMMENT '方法名称',
  `method_params` text COMMENT '接口传入参数',
  `method_desc` varchar(255) DEFAULT NULL COMMENT '方法简介说明',
  `method_url` varchar(255) DEFAULT NULL COMMENT '接口url',
  `request_type` varchar(255) DEFAULT NULL COMMENT '接口访问方式 get或post',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `is_deleted` int(1) DEFAULT '0' COMMENT '逻辑删除',
  PRIMARY KEY (`id`),
  UNIQUE KEY `method_url` (`method_url`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=104 DEFAULT CHARSET=utf8mb4;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值