【学习笔记】SpringFox+Swagger3快速入门,附代码

PS: 本文对官方英文指南进行了简单的翻译,更多操作还请转跳原文进行查看:原文指南:https://springfox.github.io/springfox/docs/3.0.0/#introduction

1. 简介

Springfox 的 Java 库套件旨在自动生成机器和人类可读的内容 使用 Spring 系列项目编写的 JSON API 规范。春狐 通过在运行时检查一次应用程序来根据 Spring 配置、类结构和 各种编译时Java注释。

1.1. 历史

Springfox是从Marty Pitt最初创建的项目演变而来 的,并被命名为“swagger-springmvc”。很多荣誉都归于马蒂 Marty。

1.2. 目标

  • 扩展对针对 JSON API 规范和文档的许多不断发展的标准的支持 如:swagger,RAMLjsonapi

  • 扩展对 spring webmvc 以外的spring技术的支持

  • 我们希望阻止使用对运行时的服务描述不重要的(swagger-core)注释。例如,注解(the jackson annotations)应始终胜过或具有比"@ApiModelProperty"或 更多的权重,例如"@NotNull"或指定 @RequestParam#required 应始终更优选。注释仅用于补充文档或在无法推断服务/模式特征的情况下覆盖/调整结果规范。

1.3. 它不是什么

由 Spring 框架贡献者认可或批准

我的项目使用的是maven进行版本管理,所以接下来更多的是基于maven的代码,gradle可以参考原文。

其他关于项目介绍省略,直接快速开始

2. 入门

2.1.依赖关系

Springfox 库托管在bintray和 jcenter 上。可以在以下位置查看和访问这些工件:

  • 发布:
    • https://jcenter.bintray.com/io/springfox/
    • http://jcenter.bintray.com/io/springfox/
  • 快照
    • http://oss.jfrog.org/simple/oss-snapshot-local/io/springfox/
    • http://oss.jfrog.org/oss-snapshot-local/io/springfox/

Springfox有多个模块,依赖关系会根据所需的API规范标准而有所不同。下面概述了如何包含生成 Swagger 2.0 API 文档的 springfox-swagger2 模块。

2.1.1.Gradle(略
2.1.2.Maven

发布版本

<pom>

    <repositories>
        <repository>
          <id>jcenter-snapshots</id>
          <name>jcenter</name>
          <url>https://jcenter.bintray.com/</url>
        </repository>
    </repositories>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
<!--   作者推荐使用上面的写法
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-oas</artifactId>
        <version>3.0.0</version>
    </dependency>
-->
</pom>
2.1.3.从现有 2.x 版本迁移
Spring引导应用程序
  1. 删除早期版本的库包含内容。具体去除springfox-swagger2springfox-swagger-ui杂物。
  2. 删除@EnableSwagger2注释
  3. 添加springfox-boot-starter
  4. Springfox 3.x 删除了对 guava 和其他第 3 方库的依赖(还不是零依赖!依赖于 spring 插件和用于注释和模型的开放 api 库),因此如果您使用 guava 谓词/函数,则需要转换为 java 8 函数接口
常规 spring mvc
  1. 删除早期版本的库包含内容。具体去除springfox-swagger2springfox-swagger-ui夹杂物。
  2. 对于 OpenAPI 添加@EnableOpenApi注释(@EnableSwagger2对于 swagger 2.0)
  3. 对于 OpenAPI 添加springfox-oas库依赖项(用于 swagger 2.0 使用springfox-swagger2
  4. Springfox 3.x 删除了对 guava 和其他第 3 方库的依赖(还不是零依赖!依赖于 spring 插件和用于注释和模型的开放 api 库),因此如果您使用 guava 谓词/函数,则需要转换为 java 8 函数接口
swagger-ui 的变化

对于非启动应用程序springfox-swagger-ui不再通过添加依赖项自动启用。它需要使用资源处理程序配置器(WebFluxConfigurerWebMvcConfigurer)显式注册。这是它的配置方式springfox-boot-starter

swagger-ui 位置已从http://host/context-path/swagger-ui.html移动到

http://host/context-path/swagger-ui/index.html

http://host/context-path/swagger-ui/

这使得它可以更好地工作,将其作为 Web jar 拉取,并在不需要时使用配置属性将其关闭。

对于 WebMvc SwaggerUIWebMvcConfigurer.java的变化
public class SwaggerUiWebMvcConfigurer implements WebMvcConfigurer {
  private final String baseUrl;

  public SwaggerUiWebMvcConfigurer(String baseUrl) {
    this.baseUrl = baseUrl;
  }

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    String baseUrl = StringUtils.trimTrailingCharacter(this.baseUrl, '/');
    registry.
        addResourceHandler(baseUrl + "/swagger-ui/**")
        .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
        .resourceChain(false);
  }

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController(baseUrl + "/swagger-ui/")
        .setViewName("forward:" + baseUrl + "/swagger-ui/index.html");
  }
}
对于 WebFlux SwaggerUIWebMvcConfigurer.java的变化
public class SwaggerUiWebFluxConfigurer implements WebFluxConfigurer {
  private final String baseUrl;

  public SwaggerUiWebFluxConfigurer(String baseUrl) {
    this.baseUrl = baseUrl;
  }

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    String baseUrl = StringUtils.trimTrailingCharacter(this.baseUrl, '/');
    registry.
        addResourceHandler(baseUrl + "/swagger-ui/**")
        .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
        .resourceChain(false);
  }
}

3. 快速入门指南

3.1. Springfox Spring MVC 和 Spring Boot

package com.zlskgroup.start.controller.swagger;

import com.fasterxml.classmate.TypeResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseBuilder;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.schema.WildcardType;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.DocExpansion;
import springfox.documentation.swagger.web.ModelRendering;
import springfox.documentation.swagger.web.OperationsSorter;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
import springfox.documentation.swagger.web.TagsSorter;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;

import java.time.LocalDate;
import java.util.List;

import static java.util.Collections.*;
import static springfox.documentation.schema.AlternateTypeRules.*;

/*
 *
 *  Copyright 2015-2018 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 * @Author zhuhuacong
 * @Date: 2023/09/28/ 14:58
 * @description springfox3官网提供的配置
 */
@Configuration
public class SpringFoxSwaggerConfig {
    @Bean
    public Docket petApi() {
        // DocketSpringfox的主要api配置机制针对swagger规范2.0初始化
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("pet")
                // select()返回 的一个实例,ApiSelectorBuilder以对通过 swagger 公开的端点进行细粒度控制。
                .select()
                // apis()允许RequestHandler使用谓词选择's。此处的示例使用any谓词(默认)。
                // 提供的现成谓词有any,none,withClassAnnotation,withMethodAnnotation和basePackage。
                .apis(RequestHandlerSelectors.any())
                // paths()允许Path使用谓词选择's。此处的示例使用any谓词(默认)。我们开箱即用地提供regex, ant, any,的谓词none。
                .paths(PathSelectors.any())
                // 配置完 api 和路径选择器后需要构建选择器
                .build()
                // 当 servlet 具有路径映射时,添加 servlet 路径映射。这会使用提供的路径映射为路径添加前缀。
                .pathMapping("/")
                // LocalDateString渲染模型属性时替换的便捷规则构建器
                .directModelSubstitute(LocalDate.class, String.class)
                .genericModelSubstitutes(ResponseEntity.class)
                // 	方便的规则生成器,用类型参数替换带有一个类型参数的泛型类型。
                // 	在此示例中ResponseEntity<T>,使用T.alternateTypeRules允许更多涉及的自定义规则。
                // 	该示例DeferredResult<ResponseEntity<T>>用Tgenerics 代替。
                .alternateTypeRules(
                        newRule(typeResolver.resolve(DeferredResult.class,
                                        typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                                typeResolver.resolve(WildcardType.class)))
                // 	指示是否需要使用默认 http 响应代码的标志
                .useDefaultResponseMessages(false)
                // 	允许全局覆盖不同 http 方法的响应消息。在此示例中,我们覆盖所有500错误状态码的GET请求,并表明它将使用响应模型
                .globalResponses(HttpMethod.GET,
                        singletonList(new ResponseBuilder()
                                .code("500")
                                .description("500 message")
                                .representation(MediaType.TEXT_XML)
                                .apply(r ->
                                        r.model(m ->
                                                // 并表明它将使用响应模型Error(也可以使用其他定义)
                                                m.referenceModel(ref ->
                                                        ref.key(k ->
                                                                k.qualifiedModelName(q ->
                                                                        q.namespace("some:namespace")
                                                                                .name("ERROR"))))))
                                .build()))
                // 设置用于保护 api 的安全方案。支持的方案有 ApiKey、BasicAuth 和 OAuth
                .securitySchemes(singletonList(apiKey()))
                // 提供一种全局设置操作安全上下文的方法。这里的想法是,我们提供一种方法来选择要受指定安全方案之一保护的操作。
                .securityContexts(singletonList(securityContext()))
                // 孵化功能,还没完成
                .enableUrlTemplating(true)
                // 允许全局配置默认路径/请求/标头参数,这些参数对于 api 的每个其余操作都很常见,但在 spring controller方法签名中不需要(例如身份验证信息)。
                // 此处添加的参数将成为生成的 swagger 规范中每个 API 操作的一部分。
                // 根据如何设置安全性,所使用的标头名称可能需要不同。
                // 覆盖此值是覆盖默认行为的一种方法。
                .globalRequestParameters(
                        singletonList(new springfox.documentation.builders.RequestParameterBuilder()
                                .name("someGlobalParameter")
                                .description("Description of someGlobalParameter")
                                .in(ParameterType.QUERY)
                                .required(true)
                                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                                .build()))
                // 	添加标签是定义服务/操作可以选择的所有可用标签的一种方法。目前只有名称和描述
                .tags(new Tag("Pet Service", "All apis relating to pets"));
                // 应用程序中是否存在不可“访问”的模型?不可到达是指我们想要描述模型但未在任何操作中明确使用。
//                .additionalModels(typeResolver.resolve(AdditionalModel.class));
    }

    @Autowired
    private TypeResolver typeResolver;

    private final String KEY = "mykey";

    // 这里我们使用 ApiKey 作为通过名称标识的安全模式 mykey
    private ApiKey apiKey() {

        return new ApiKey(KEY, "api_key", "header");
    }

    // 此安全上下文适用的路径选择器。
    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("/anyPath.*"))
                .build();
    }

    // 这里我们使用安全方案中定义的相同密钥mykey
    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope
                = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return singletonList(
                new SecurityReference(KEY, authorizationScopes));
    }

    @Bean
    //  用于 oauth 和 apiKey 设置的可选 swagger-ui 安全配置
    SecurityConfiguration security() {
        return SecurityConfigurationBuilder.builder()
                .clientId("test-app-client-id")
                .clientSecret("test-app-client-secret")
                .realm("test-app-realm")
                .appName("test-app")
                .scopeSeparator(",")
                // 附加的字符串参数
                .additionalQueryStringParams(null)
                // 将基本身份验证与访问代码授予一起使用
                .useBasicAuthenticationWithAccessCodeGrant(false)
                // 启用Csrf支持
                .enableCsrfSupport(false)
                .build();
    }

    @Bean
    // 可选 的swagger-ui ui配置目前只支持验证url
    UiConfiguration uiConfig() {
        return UiConfigurationBuilder.builder()
                .deepLinking(true)
                .displayOperationId(false)
                .defaultModelsExpandDepth(1)
                .defaultModelExpandDepth(1)
                .defaultModelRendering(ModelRendering.EXAMPLE)
                .displayRequestDuration(false)
                .docExpansion(DocExpansion.NONE)
                .filter(false)
                .maxDisplayedTags(null)
                .operationsSorter(OperationsSorter.ALPHA)
                .showExtensions(false)
                .showCommonExtensions(false)
                .tagsSorter(TagsSorter.ALPHA)
                .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
                .validatorUrl(null)
                .build();
    }

}

3.2.配置说明

该库广泛使用谷歌的guava工具库。例如,当您看到newArrayList(…)等等

  1. 启用 Springfox swagger 2
  2. 指示 spring 在哪里扫描 API 控制器
  3. DocketSpringfox的主要api配置机制针对swagger规范2.0初始化
  4. select()返回 的一个实例,ApiSelectorBuilder以对通过 swagger 公开的端点进行细粒度控制。
  5. apis()允许RequestHandler使用谓词选择’s。此处的示例使用any谓词(默认)。提供的现成谓词有any,none,withClassAnnotation,withMethodAnnotation和basePackage。
  6. paths()允许Path使用谓词选择’s。此处的示例使用any谓词(默认)。我们开箱即用地提供regex, ant, any,的谓词none。
  7. 配置完 api 和路径选择器后需要构建选择器。
  8. 当 servlet 具有路径映射时,添加 servlet 路径映射。这会使用提供的路径映射为路径添加前缀。
  9. LocalDate,String渲染模型属性时替换的便捷规则构建器
  10. 方便的规则生成器,用类型参数替换带有一个类型参数的泛型类型。
    • 在此示例中ResponseEntity<T>,使用T.alternateTypeRules允许更多涉及的自定义规则。
    • 该示例DeferredResult<ResponseEntity<T>>Tgenerics 代替。
  11. 指示是否需要使用默认 http 响应代码的标志。
  12. 允许全局覆盖不同 http 方法的响应消息。在此示例中,我们覆盖所有请求的 500 错误代码GET
  13. 并表明它将使用响应模型Error(并表明它将使用响应模型Error(也可以使用其他定义)
  14. 设置用于保护 api 的安全方案。支持的方案有 ApiKey、BasicAuth 和 OAuth
  15. 提供一种全局设置操作安全上下文的方法。这里的想法是,我们提供一种方法来选择要受指定安全方案之一保护的操作。
  16. 这里我们使用 ApiKey 作为通过名称标识的安全模式mykey
  17. 此安全上下文适用的路径选择器。
  18. 这里我们使用安全方案中定义的相同密钥mykey
  19. 用于 oauth 和 apiKey 设置的可选 swagger-ui 安全配置
  20. 可选的swagger-ui ui配置目前只支持验证url
  21. 孵化 设置此标志向处理器发出信号,表明生成的路径应尝试使用表单样式查询扩展。因此,我们可以区分具有相同路径主干但查询字符串组合不同的路径。例如,有两个 api:首先, http://example.org/findCustomersBy?name =Test 按名称查找客户。根据RFC 6570 ,这将表示为http://example.org/findCustomersBy{?name} 。其次, http://example.org/findCustomersBy? zip=76051 通过 zip 查找客户。根据RFC 6570 ,这将表示为http://example.org/findCustomersBy{?zip} 。
  22. 允许全局配置默认路径/请求/标头参数,这些参数对于 api 的每个其余操作都很常见,但在 spring 控制器方签名中不需要(例如身份验证信息)。
    • 此处添加的参数将成为生成的 swagger 规范中每个 API 操作的一部分。
    • 根据如何设置安全性,所使用的标头名称可能需要不同。覆盖此值是覆盖默认行为的一种方法。
  23. 添加标签是定义服务/操作可以选择的所有可用标签的一种方法。目前只有名称和描述。
  24. 应用程序中是否存在不可“访问”的模型?不可到达是指我们想要描述模型但未在任何操作中明确使用。一个示例是返回序列化为字符串的模型的操作。我们确实想传达字符串模式的期望。这正是做到这一点的一种方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Xcong_Zhu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值