spring-swagger获取接口url和接口名称
在spring boot 项目,很多使用 swagger 做接口文档编写。但是怎么集中获取 项目内接口url。通过查看 swagger接口,提取如下代码
参考:springboot获取所有URL和swagger注解参数
工具类
抱歉给漏了自定义类了
package cn.xxx.xxx.xx.commons.web;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* SpringBeanManage 类说明:
*
* @version v1.0
* @date 2021/11/15
*/
@Component
public class SpringBeanManage implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
if (null == SpringBeanManage.context){
SpringBeanManage.context = context;
}
}
public static ApplicationContext getContext() {
return context;
}
public static <T> T getBean(String name,Class<T> clazz){
return getContext().getBean(name, clazz);
}
public static <T> T getBean(String name){
return (T) getContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz){
return getContext().getBean(clazz);
}
public static boolean contain(String name){
return getContext().containsBean(name);
}
}
代码
import cn.xxx.xxx.xx.commons.web.SpringBeanManage;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.Swagger;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import springfox.documentation.service.Documentation;
import springfox.documentation.spring.web.DocumentationCache;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2Mapper;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
/**
* 启动后执行
*
* @version v1.0
* @date 2021/11/12
*/
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
private static final Logger logger = LoggerFactory.getLogger(ApplicationRunnerImpl.class);
@Override
public void run(ApplicationArguments args) throws Exception {
logger.info(">>>>>>>>>>>>>>成功启动>>>>>>>>>>>>>");
swaggerPaths();
paths();
}
private SwaggerResourcesProvider resourcesProvider;
private DocumentationCache documentationCache;
private ServiceModelToSwagger2Mapper mapper;
@Autowired
public void setResourcesProvider(SwaggerResourcesProvider resourcesProvider) {
this.resourcesProvider = resourcesProvider;
}
@Autowired
public void setDocumentationCache(DocumentationCache documentationCache) {
this.documentationCache = documentationCache;
}
@Autowired
public void setMapper(ServiceModelToSwagger2Mapper mapper) {
this.mapper = mapper;
}
private void paths() throws Exception {
RequestMappingHandlerMapping mapping = SpringBeanManage.getBean(RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
Map<String, String> map = new HashMap<>(handlerMethods.size());
for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
HandlerMethod value = entry.getValue();
String name = value.getMethod().getDeclaringClass().getName();
String methodName = value.getMethod().getName();
if(name.contains("com.com.controller") && name.endsWith("Controller")){
Class<?> clazz = Class.forName(value.getMethod().getDeclaringClass().getName());
Method[] declaredMethods = clazz.getDeclaredMethods();
RequestMappingInfo key = entry.getKey();
PatternsRequestCondition patternsCondition = key.getPatternsCondition();
Optional<String> first = patternsCondition.getPatterns().stream().filter(Objects::nonNull).findFirst();
if(!first.isPresent()){
continue;
}
String url = first.get();
Arrays.stream(declaredMethods).forEach(c -> {
if(c.getName().equals(methodName)){
ApiOperation annotation = c.getAnnotation(ApiOperation.class);
if( null != annotation ){
map.put(url,annotation.value());
}
}
});
}
}
String jsonString = JSON.toJSONString(map, true);
logger.info("提取项目内 接口路径,{}",jsonString);
}
private void swaggerPaths() {
Set<String> groups = resourcesProvider.get().stream().map(SwaggerResource::getName).collect(Collectors.toSet());
Map<String, Map<String, String>> mapMap = new HashMap<>(groups.size());
Documentation documentation;
Swagger swagger;
for (String group : groups) {
documentation = documentationCache.documentationByGroup(group);
swagger = mapper.mapDocumentation(documentation);
Map<String, String> one = new HashMap<>(swagger.getPaths().size());
swagger.getPaths().forEach((k,v) -> {
String summary = v.getOperations().get(0).getSummary();
if(StringUtils.isEmpty(summary)){
one.put(k,k);
}else {
one.put(k,summary);
}
});
mapMap.put(group,one);
}
String jsonString = JSON.toJSONString(mapMap, true);
logger.info("通过swagger 提取项目内 接口路径,{}",jsonString);
}
}
日志输出
>>>>>>>>>>>>>>成功启动>>>>>>>>>>>>>
通过swagger 提取项目内 接口路径,{
"模块1":{
"/version":"版本"
},
"模块2":{
"/common/healthy":"健康检查"
}
}
提取项目内 接口路径,{
"/version":"版本",
"/common/healthy":"健康检查"
}
代码二
import com.alibaba.fastjson.JSON;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import springfox.documentation.service.Documentation;
import springfox.documentation.spring.web.DocumentationCache;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2Mapper;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* 启动后执行
*
* @author z.y.l
* @version v1.0
* @date 2021/11/12
*/
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
private static final Logger logger = LoggerFactory.getLogger(ApplicationRunnerImpl.class);
@Override
public void run(ApplicationArguments args) throws Exception {
logger.info(">>>>>>>>>>>>>>成功启动>>>>>>>>>>>>>");
swaggerPaths();
}
private SwaggerResourcesProvider resourcesProvider;
private DocumentationCache documentationCache;
private ServiceModelToSwagger2Mapper mapper;
@Autowired
public void setResourcesProvider(SwaggerResourcesProvider resourcesProvider) {
this.resourcesProvider = resourcesProvider;
}
@Autowired
public void setDocumentationCache(DocumentationCache documentationCache) {
this.documentationCache = documentationCache;
}
@Autowired
public void setMapper(ServiceModelToSwagger2Mapper mapper) {
this.mapper = mapper;
}
private void swaggerPaths() {
Set<String> groups = resourcesProvider.get().stream().map(SwaggerResource::getName).collect(Collectors.toSet());
Map<String, Map<String, String>> mapMap = new HashMap<>(groups.size());
Documentation documentation;
Swagger swagger;
for (String group : groups) {
documentation = documentationCache.documentationByGroup(group);
swagger = mapper.mapDocumentation(documentation);
Map<String, String> one = new TreeMap<>();
swagger.getPaths().forEach((k,v) -> {
Operation operation = v.getOperations().get(0);
String summary = operation.getSummary();
String id = operation.getOperationId();
String[] split = id.split("Using");
if(StringUtils.isEmpty(summary)){
one.put(k,'['+split[1]+']'+split[0]);
}else {
one.put(k,'['+split[1]+']'+summary);
}
});
mapMap.put(group,one);
}
String jsonString = JSON.toJSONString(mapMap, true);
logger.info("通过swagger 提取项目内 接口路径,{}",jsonString);
}
}
日志输出
>>>>>>>>>>>>>>成功启动>>>>>>>>>>>>>
通过swagger 提取项目内 接口路径,{
"模块1":{
"/version":"[GET]版本"
},
"模块2":{
"/common/healthy":"[GET]健康检查"
}
}
代码三
import com.alibaba.fastjson.JSON;
import com.google.common.collect.TreeMultimap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import springfox.documentation.service.ApiDescription;
import springfox.documentation.service.ApiListing;
import springfox.documentation.service.Documentation;
import springfox.documentation.service.Tag;
import springfox.documentation.spring.web.DocumentationCache;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* 启动后执行
*
* @author z.y.l
* @version v1.0
* @date 2021/11/12
*/
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
private static final Logger logger = LoggerFactory.getLogger(ApplicationRunnerImpl.class);
@Override
public void run(ApplicationArguments args) throws Exception {
logger.info(">>>>>>>>>>>>>>成功启动>>>>>>>>>>>>>");
swaggerPaths();
}
private SwaggerResourcesProvider resourcesProvider;
private DocumentationCache documentationCache;
private ServiceModelToSwagger2Mapper mapper;
@Autowired
public void setResourcesProvider(SwaggerResourcesProvider resourcesProvider) {
this.resourcesProvider = resourcesProvider;
}
@Autowired
public void setDocumentationCache(DocumentationCache documentationCache) {
this.documentationCache = documentationCache;
}
@Autowired
public void setMapper(ServiceModelToSwagger2Mapper mapper) {
this.mapper = mapper;
}
private void swaggerPaths() {
Set<String> groups = resourcesProvider.get().stream().map(SwaggerResource::getName).collect(Collectors.toSet());
Map<String, Map<String, Map<String, String>>> mmm = new HashMap<>(groups.size());
Documentation documentation;
TreeMultimap<String, ApiListing> apiListings;
Map<String, String> one;
Map<String, Map<String, String>> apiMap;
String k , v;
ApiListing apis;
Set<Tag> set;
for (String group : groups) {
documentation = documentationCache.documentationByGroup(group);
apiMap = new TreeMap<>();
apiListings = (TreeMultimap<String, ApiListing>)documentation.getApiListings();
for (String g : apiListings.keySet()) {
k = null;
apis = apiListings.get(g).first();
if (null != (set = apis.getTags()) && !set.isEmpty()) {
k = set.stream().findFirst().get().getName();
}
if(StringUtils.isBlank(k)){
k = apis.getBasePath();
}
if(apiMap.containsKey(k)){
one = apiMap.get(k);
}else{
one = new TreeMap<>();
apiMap.put(k,one);
}
for (ApiDescription api : apis.getApis()) {
v = api.getOperations().get(0).getSummary();
if(StringUtils.isBlank(v)){
v = api.getDescription();
}
one.put(api.getPath(),'['+api.getOperations().get(0).getMethod().name() +']'+ v);
}
}
mmm.put(group,apiMap);
}
String jsonString = JSON.toJSONString(mmm, true);
logger.info("通过swagger 提取项目内 接口路径,{}",jsonString);
}
}
日志输出
>>>>>>>>>>>>>>成功启动>>>>>>>>>>>>>
通过swagger 提取项目内 接口路径,{
"模块1":{
"root接口":{
"/version":"[GET]版本"
}
},
"模块2":{
"公共接口":{
"/common/healthy":"[GET]健康检查"
}
}
}