PS: 本文对官方英文指南进行了简单的翻译,更多操作还请转跳原文进行查看:原文指南:https://springfox.github.io/springfox/docs/3.0.0/#introduction
文章目录
- 1. 简介
- 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. 快速入门指南
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引导应用程序
- 删除早期版本的库包含内容。具体去除
springfox-swagger2
和springfox-swagger-ui
杂物。 - 删除
@EnableSwagger2
注释 - 添加
springfox-boot-starter
- Springfox 3.x 删除了对 guava 和其他第 3 方库的依赖(还不是零依赖!依赖于 spring 插件和用于注释和模型的开放 api 库),因此如果您使用 guava 谓词/函数,则需要转换为 java 8 函数接口
常规 spring mvc
- 删除早期版本的库包含内容。具体去除
springfox-swagger2
和springfox-swagger-ui
夹杂物。 - 对于 OpenAPI 添加
@EnableOpenApi
注释(@EnableSwagger2
对于 swagger 2.0) - 对于 OpenAPI 添加
springfox-oas
库依赖项(用于 swagger 2.0 使用springfox-swagger2
) - Springfox 3.x 删除了对 guava 和其他第 3 方库的依赖(还不是零依赖!依赖于 spring 插件和用于注释和模型的开放 api 库),因此如果您使用 guava 谓词/函数,则需要转换为 java 8 函数接口
swagger-ui 的变化
对于非启动应用程序
springfox-swagger-ui
不再通过添加依赖项自动启用。它需要使用资源处理程序配置器(WebFluxConfigurer
或WebMvcConfigurer
)显式注册。这是它的配置方式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(…)
等等
- 启用 Springfox swagger 2
- 指示 spring 在哪里扫描 API 控制器
- DocketSpringfox的主要api配置机制针对swagger规范2.0初始化
- select()返回 的一个实例,ApiSelectorBuilder以对通过 swagger 公开的端点进行细粒度控制。
- apis()允许RequestHandler使用谓词选择’s。此处的示例使用any谓词(默认)。提供的现成谓词有any,none,withClassAnnotation,withMethodAnnotation和basePackage。
- paths()允许Path使用谓词选择’s。此处的示例使用any谓词(默认)。我们开箱即用地提供regex, ant, any,的谓词none。
- 配置完 api 和路径选择器后需要构建选择器。
- 当 servlet 具有路径映射时,添加 servlet 路径映射。这会使用提供的路径映射为路径添加前缀。
- LocalDate,String渲染模型属性时替换的便捷规则构建器
- 方便的规则生成器,用类型参数替换带有一个类型参数的泛型类型。
- 在此示例中
ResponseEntity<T>
,使用T.alternateTypeRules允许更多涉及的自定义规则。 - 该示例
DeferredResult<ResponseEntity<T>>
用Tgenerics
代替。
- 在此示例中
- 指示是否需要使用默认 http 响应代码的标志。
- 允许全局覆盖不同 http 方法的响应消息。在此示例中,我们覆盖所有请求的 500 错误代码GET
- 并表明它将使用响应模型Error(并表明它将使用响应模型Error(也可以使用其他定义)
- 设置用于保护 api 的安全方案。支持的方案有 ApiKey、BasicAuth 和 OAuth
- 提供一种全局设置操作安全上下文的方法。这里的想法是,我们提供一种方法来选择要受指定安全方案之一保护的操作。
- 这里我们使用 ApiKey 作为通过名称标识的安全模式mykey
- 此安全上下文适用的路径选择器。
- 这里我们使用安全方案中定义的相同密钥mykey
- 用于 oauth 和 apiKey 设置的可选 swagger-ui 安全配置
- 可选的swagger-ui ui配置目前只支持验证url
- 孵化 设置此标志向处理器发出信号,表明生成的路径应尝试使用表单样式查询扩展。因此,我们可以区分具有相同路径主干但查询字符串组合不同的路径。例如,有两个 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} 。
- 允许全局配置默认路径/请求/标头参数,这些参数对于 api 的每个其余操作都很常见,但在 spring 控制器方签名中不需要(例如身份验证信息)。
- 此处添加的参数将成为生成的 swagger 规范中每个 API 操作的一部分。
- 根据如何设置安全性,所使用的标头名称可能需要不同。覆盖此值是覆盖默认行为的一种方法。
- 添加标签是定义服务/操作可以选择的所有可用标签的一种方法。目前只有名称和描述。
- 应用程序中是否存在不可“访问”的模型?不可到达是指我们想要描述模型但未在任何操作中明确使用。一个示例是返回序列化为字符串的模型的操作。我们确实想传达字符串模式的期望。这正是做到这一点的一种方法。