spring boot + swagger3实现接口文档,获取全部url清单

集成swagger

springboot集成

  • pom依赖
		<!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-ui</artifactId>
            <version>3.0.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.plugin</groupId>
            <artifactId>spring-plugin-core</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <!--swagger-->
  • config
/**
 * @author code
 * @version 1.0
 * @Date 2022/9/22 9:58
 * @Description ${swagger配置类}
 */
@Configuration
@EnableOpenApi
@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
@EnableAutoConfiguration
public class SwaggerConfig {

    @Bean
    @ConditionalOnMissingBean
    public SwaggerProperties swaggerProperties(){
        return new SwaggerProperties();
    }

    /**
     * 配置类,扫描指定的包并分组
     * @return
     */
    @Bean
    public Docket docket(SwaggerProperties swaggerProperties){
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo(swaggerProperties))
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                .paths(PathSelectors.regex("/error.*").negate())
                .paths(PathSelectors.any())
                .build().globalRequestParameters(parameters());
    }

    private ApiInfo apiInfo(SwaggerProperties swaggerProperties) {
        return new ApiInfoBuilder().title(swaggerProperties.getTitle()).description(swaggerProperties.getDescription()).version(swaggerProperties.getVersion()).build();
    }

    private List<RequestParameter> parameters(){
        List<RequestParameter> globalRequestParamters = new ArrayList<>();
        RequestParameter requestParameter = new RequestParameterBuilder()
                .name("authorization")
                .description("test")
                .in(ParameterType.HEADER)
                .required(false)
                .build();
        globalRequestParamters.add(requestParameter);
        return globalRequestParamters;
    }
}
  • properties
/**
 * @author code
 * @version 1.0
 * @Date 2022/9/22 14:10
 * @Description ${DESCRIPTION}
 */
@Data
@Component
@ConfigurationProperties("swagger")
public class SwaggerProperties {
    private String title;
    private String description;
    private String version;
    private String basePackage;

    public String getTitle() {
        return title;
    }

    public SwaggerProperties setTitle(String title) {
        this.title = title;
        return this;
    }

    public String getDescription() {
        return description;
    }

    public SwaggerProperties setDescription(String description) {
        this.description = description;
        return this;
    }

    public String getVersion() {
        return version;
    }

    public SwaggerProperties setVersion(String version) {
        this.version = version;
        return this;
    }

    public String getBasePackage() {
        return basePackage;
    }

    public SwaggerProperties setBasePackage(String basePackage) {
        this.basePackage = basePackage;
        return this;
    }
}
  • 配置文件
swagger.enabled=true
swagger.basePackage=com.fwpt.modules.system.controller
swagger.description=system
swagger.title=system

获取api清单

/**
 * @author code
 * @version 1.0
 * @Date 2022/9/28 16:06
 * @Description ${获取api清单}
 */
@RestController
public class ApiCollectController {

    @Autowired
    WebApplicationContext webApplicationContext;

    @Autowired
    RequestMappingHandlerMapping mapping;

    @ApiIgnore
    @RequestMapping(value = "/getAllUrls",method = RequestMethod.GET)
    public List<Map<String,Object>> getAllUrls(){
        List<Map<String,Object>> list = new ArrayList<>();
        Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = mapping.getHandlerMethods();
        for(Map.Entry<RequestMappingInfo,HandlerMethod> entry : handlerMethodMap.entrySet()){
            //去掉swagger接口
            String className = entry.getValue().getMethod().getDeclaringClass().getName();
            if(ObjectUtils.isEmpty(className) || className.contains("SwaggerConfig")){
                continue;
            }
            Map<String,Object> map = new HashMap<>(16);
            map.putAll(getSwaggerProperties(entry.getValue()));
            map.put("requestType", getRequestType(entry.getKey().getMethodsCondition()));
            map.put("requestServer", webApplicationContext.getEnvironment().getProperty("spring.application.name"));
            // 一个方法可能对应多个url
            PatternsRequestCondition patternsCondition = entry.getKey().getPatternsCondition();
            for (String url : patternsCondition.getPatterns()) {
                map.put("requestUrl", getRequestUrl(url));
                list.add(map);
            }

        }
        return list;
    }

    private Map<String, Object> getSwaggerProperties(HandlerMethod handlerMethod) {
        Map<String, Object> map = new HashMap<>(16);
        // 完整接口信息:类名信息 + 接口方法信息
        String requestName = "";
        // 接口方法补充描述
        String remark = "";

        // 类名的备注信息
        Api api = handlerMethod.getMethod().getDeclaringClass().getAnnotation(Api.class);
        if (handlerMethod.getMethod().getDeclaringClass().isAnnotationPresent(Api.class) && Objects.nonNull(api)) {
            requestName = api.value();
        }
        // 接口方法名的备注信息
        ApiOperation apiOperation = handlerMethod.getMethodAnnotation(ApiOperation.class);
        if (handlerMethod.hasMethodAnnotation(ApiOperation.class) && Objects.nonNull(apiOperation)) {
            requestName = ObjectUtils.isEmpty(requestName) ? apiOperation.value() : requestName + "_" + apiOperation.value();
            remark = ObjectUtils.isEmpty(apiOperation.notes()) ? "" : apiOperation.notes();
        } else {
            requestName = ObjectUtils.isEmpty(requestName) ? handlerMethod.getMethod().getName() : requestName + "_" + handlerMethod.getMethod().getName();
        }
        map.put("requestName", requestName);
        map.put("remark", remark);
        return map;
    }

    private String getRequestType(RequestMethodsRequestCondition methodsCondition) {
        // 如果多个,改为一个POST
        String requestType = null;
        int count = 0;
        for (RequestMethod requestMethod : methodsCondition.getMethods()) {
            requestType = requestMethod.toString();
            count++;
        }
        return requestType == null || count > 1 ? "POST" : requestType;
    }

    private String getRequestUrl(String url) {
        String separator = "/";
        String separator2 = "//";
        String separator3 = "///";
        String contextPath = webApplicationContext.getEnvironment().getProperty("server.servlet.context-path");
        String requestUrl;
        if (!ObjectUtils.isEmpty(contextPath) && !separator.equals(contextPath)) {
            requestUrl = contextPath + url;
            if (requestUrl.contains(separator3) || requestUrl.contains(separator2)) {
                requestUrl = requestUrl.replace(separator3, separator);
                requestUrl = requestUrl.replace(separator2, separator);
            }
        } else {
            requestUrl = url;
        }
        return requestUrl;
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值