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

2023-10-13 16:12

本文主要是介绍【学习笔记】SpringFox+Swagger3快速入门,附代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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

文章目录

    • 1. 简介
      • 1.1. 历史
      • 1.2. 目标
      • 1.3. 它不是什么
    • 2. 入门
      • 2.1.依赖关系
        • 2.1.1.Gradle(略
        • 2.1.2.Maven
        • 2.1.3.从现有 2.x 版本迁移
          • Spring引导应用程序
          • 常规 spring mvc
          • swagger-ui 的变化
          • 对于 WebMvc [SwaggerUIWebMvcConfigurer.java](https://github.com/springfox/springfox/blob/master/springfox-boot-starter/src/main/java/springfox/boot/starter/autoconfigure/SwaggerUiWebMvcConfigurer.java)的变化
          • 对于 WebFlux [SwaggerUIWebMvcConfigurer.java](https://github.com/springfox/springfox/blob/master/springfox-boot-starter/src/main/java/springfox/boot/starter/autoconfigure/SwaggerUiWebFluxConfigurer.java)的变化
    • 3. 快速入门指南
      • 3.1. Springfox Spring MVC 和 Spring Boot
      • 3.2.配置说明

1. 简介

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

1.1. 历史

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

1.2. 目标

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

  • 扩展对 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;}@Overridepublic 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);}@Overridepublic 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;}@Overridepublic 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 {@Beanpublic 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));}@Autowiredprivate TypeResolver typeResolver;private final String KEY = "mykey";// 这里我们使用 ApiKey 作为通过名称标识的安全模式 mykeyprivate ApiKey apiKey() {return new ApiKey(KEY, "api_key", "header");}// 此安全上下文适用的路径选择器。private SecurityContext securityContext() {return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("/anyPath.*")).build();}// 这里我们使用安全方案中定义的相同密钥mykeyList<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配置目前只支持验证urlUiConfiguration 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. 应用程序中是否存在不可“访问”的模型?不可到达是指我们想要描述模型但未在任何操作中明确使用。一个示例是返回序列化为字符串的模型的操作。我们确实想传达字符串模式的期望。这正是做到这一点的一种方法。

这篇关于【学习笔记】SpringFox+Swagger3快速入门,附代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/204405

相关文章

Python中OpenCV与Matplotlib的图像操作入门指南

《Python中OpenCV与Matplotlib的图像操作入门指南》:本文主要介绍Python中OpenCV与Matplotlib的图像操作指南,本文通过实例代码给大家介绍的非常详细,对大家的学... 目录一、环境准备二、图像的基本操作1. 图像读取、显示与保存 使用OpenCV操作2. 像素级操作3.

IIS 7.0 及更高版本中的 FTP 状态代码

《IIS7.0及更高版本中的FTP状态代码》本文介绍IIS7.0中的FTP状态代码,方便大家在使用iis中发现ftp的问题... 简介尝试使用 FTP 访问运行 Internet Information Services (IIS) 7.0 或更高版本的服务器上的内容时,IIS 将返回指示响应状态的数字代

MySQL 添加索引5种方式示例详解(实用sql代码)

《MySQL添加索引5种方式示例详解(实用sql代码)》在MySQL数据库中添加索引可以帮助提高查询性能,尤其是在数据量大的表中,下面给大家分享MySQL添加索引5种方式示例详解(实用sql代码),... 在mysql数据库中添加索引可以帮助提高查询性能,尤其是在数据量大的表中。索引可以在创建表时定义,也可

使用C#删除Excel表格中的重复行数据的代码详解

《使用C#删除Excel表格中的重复行数据的代码详解》重复行是指在Excel表格中完全相同的多行数据,删除这些重复行至关重要,因为它们不仅会干扰数据分析,还可能导致错误的决策和结论,所以本文给大家介绍... 目录简介使用工具C# 删除Excel工作表中的重复行语法工作原理实现代码C# 删除指定Excel单元

Python实现一键PDF转Word(附完整代码及详细步骤)

《Python实现一键PDF转Word(附完整代码及详细步骤)》pdf2docx是一个基于Python的第三方库,专门用于将PDF文件转换为可编辑的Word文档,下面我们就来看看如何通过pdf2doc... 目录引言:为什么需要PDF转Word一、pdf2docx介绍1. pdf2docx 是什么2. by

Spring Security介绍及配置实现代码

《SpringSecurity介绍及配置实现代码》SpringSecurity是一个功能强大的Java安全框架,它提供了全面的安全认证(Authentication)和授权(Authorizatio... 目录简介Spring Security配置配置实现代码简介Spring Security是一个功能强

通过cmd获取网卡速率的代码

《通过cmd获取网卡速率的代码》今天从群里看到通过bat获取网卡速率两段代码,感觉还不错,学习bat的朋友可以参考一下... 1、本机有线网卡支持的最高速度:%v%@echo off & setlocal enabledelayedexpansionecho 代码开始echo 65001编码获取: >

Java集成Onlyoffice的示例代码及场景分析

《Java集成Onlyoffice的示例代码及场景分析》:本文主要介绍Java集成Onlyoffice的示例代码及场景分析,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 需求场景:实现文档的在线编辑,团队协作总结:两个接口 + 前端页面 + 配置项接口1:一个接口,将o

SpringBoot实现Kafka动态反序列化的完整代码

《SpringBoot实现Kafka动态反序列化的完整代码》在分布式系统中,Kafka作为高吞吐量的消息队列,常常需要处理来自不同主题(Topic)的异构数据,不同的业务场景可能要求对同一消费者组内的... 目录引言一、问题背景1.1 动态反序列化的需求1.2 常见问题二、动态反序列化的核心方案2.1 ht

MybatisX快速生成增删改查的方法示例

《MybatisX快速生成增删改查的方法示例》MybatisX是基于IDEA的MyBatis/MyBatis-Plus开发插件,本文主要介绍了MybatisX快速生成增删改查的方法示例,文中通过示例代... 目录1 安装2 基本功能2.1 XML跳转2.2 代码生成2.2.1 生成.xml中的sql语句头2