有時咱們須要接口的一些基本信息,好比接口請求路徑,接口請求方式等,咱們用這些信息來作判斷,或者入庫。數據庫
我在開發接口權限的時候就遇到了這個問題,以前寫的接口不少,如今須要將這些接口信息存到數據庫中,api
用來作接口的權限操做,通過一番查閱,在此彙總了一下:app
@Autowired WebApplicationContext applicationContext; @RequestMapping(value = "/getAllURL", method = RequestMethod.POST) public Object 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()); // 方法名 Annotation[] annotations = handlerMethod.getMethod().getDeclaredAnnotations(); if (annotations != null) { // 處理具體的方法信息 for (Annotation annotation : annotations) { if (annotation instanceof ApiOperation) { ApiOperation methodDesc = (ApiOperation) annotation; String desc = methodDesc.value(); 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); } return JSONArray.fromObject(resultList); }