Swagger3

Swagger3

什么是 Swagger

Swagger 是一系列 RESTful API 的工具,通过 Swagger 可以获得项目的⼀种交互式文档,客户端 SDK 的自动生成等功能。

Swagger 的目标是为 REST APIs 定义一个标准的、与语⾔言无关的接口,使人和计算机在看不到源码或者看不到文档或者不能通过网络流量检测的情况下,能发现和理解各种服务的功能。当服务通过 Swagger 定义,消费者就能与远程的服务互动通过少量的实现逻辑。

Swagger(丝袜哥)是世界上最流行的 API 表达工具。

了解
Swagger 从 3.0 版本开始更名为:OpenAPI 。

所以按惯例,通常所说的 Swagger 指的是 2.x 版本,而 OpenAPI 则指的是 3.0 版本。

《Swagger2 和 Swagger3 的不同》

后续,我们使用的是 Swagger 3 。

使用 Spring Boot 集成 Swagger 的理念是,使用用注解来标记出需要在 API 文档中展示的信息,Swagger 会根据项目中标记的注解来生成对应的 API 文档。Swagger 被号称世界上最流行的 API 工具,它提供了 API 管理的全套解决方案,API 文档管理需要考虑的因素基本都包含,这里将讲解最常用的定制内容。

Spring Boot 集成 Swagger 3 很简单,需要引入依赖并做基础配置即可。

第 1 步:引入 pom 依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

第 2 步:创建 SwaggerConfig 配置类

@Configuration
@EnableOpenApi // 默认。可省略。
public class SwaggerConfig {
}

第 3 步:进行配置

在 SwaggerConfig 类中添加 2 个方法:(其中一个方法是为另一个方法作辅助的准备工作)

import static springfox.documentation.builders.RequestHandlerSelectors.*;
import static springfox.documentation.builders.PathSelectors.*;

@Bean
public Docket api() {
    return new Docket(DocumentationType.OAS_30)
        .apiInfo(apiInfo())
        .enable(true)  // 使用使用 swagger 开关。默认 true ,可省略。
        .select()
//      .apis(basePackage("xxx.yyy.zzz"))            // 扫描指定包路径
//      .apis(withClassAnnotation(Api.class))        // 以 @Api 注解为依据进行扫描
        .apis(withMethodAnnotation(Operation.class)) // 以 @ApiOperation 注解为依据进行扫描
//      .apis(withClassAnnotation(Api.class))        // 以 @Api 注解为依据进行扫描
        .paths(any())   // 过滤器:对外暴露所有 URI
//      .paths(none())  // 过滤器:一个 URI 都不对外暴露
//      .paths(ant())   // 过滤器:对外暴露符合 ANT 风格正则表达式的 URI
//      .paths(regex()  // 过滤器:对外暴露符合正则表达式的 URI
        .build();
}

此方法使用 @Bean 注解,在启动时初始化,返回实例 Docket(Swagger API 摘要对象),这里需要注意的是 .apis(basePackage(“xxx.yyy.zzz”)) 指定需要扫描的包路路径,只有此路径下的 Controller 类才会自动生成 Swagger 扫描,而扫描到的这些 URI 也不一定是都对外暴露( 生成在线文档 ),对外暴露哪些,取决于下面的 .paths() 方法过滤。

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
       .title("XXX 项目接口文挡") //  可以用来自定义API的主标题
       .description("XXX Project Swagger 3 UserService Interface") // 可以用来描述整体的API
       .version("1.0") // 可以用来定义版本。
       .build();
}

这块配置相对重要一些,主要配置页面展示的基本信息包括:标题、描述、版本、服务条款等,查看 ApiInfo 类的源码还会发现支持 license 等更多的配置。

第 4 步:使用 @Api 和 @Operation 注解

@Api 注解标注在 Controller 类上,而 @Operation 注解标注在 Controller 的方法上。

@Api( tags = {"用户管理", "xxx管理", "yyy管理"} ) // tags 故意有"多余"
...
public class UserController {

    @Operation( summary = "查询所有用户信息", description = "查询所有用户信息", method="GET" )
    ...
    public List<UserVo> listUsers() {
        ...
    }

    @Operation( summary = "查询用户信息", description = "通过 ID 查询用户信息", method="GET" )
    ...
    public ResultResponse<UserVo> getUser(long id) {
        ...
    }
}

第 5 步:使用 @Parameter 注解

@Parameter 注解用在 Controller 方法的参数上。

public String helloUsingGET(
        @Parameter(in = ParameterIn.QUERY, description = "用户名", required = true) @RequestParam(value = "username") String username,
        @Parameter(in = ParameterIn.QUERY, description = "密码", required = true) @RequestParam(value = "password") String password) {
    ...
}

@Parameter 注解的 in 属性的属性值有 4 种:query、header、path 和 cookie 。它们都是用来描述请求参数不是在请求体的情况下,会在哪里:

query(配合 GET 请求 + @RequestParam 注解使用)
表示参数是以 query string 的形式携带在 HTTP 请求行中。即,拼接在 URL 的后面。

header(配合 @RequestHeader 注解使用 )
表示参数是"藏在"HTTP 请求头中传递到后台的。

path( 配合 @PathVariable 注解使用 )
表示参数是"嵌在"路径中的,即,称为 URL 的一部分。

cookie
表示参数是以 cookie 的方式传递到后台的,使用较少。

第 6 步:@Schema 注解

@Schema 注解用在 JavaBean 及其属性上,用来指定 Controller 所使用的 FO 和 VO/DTO。

@Schema(description = "用户登录信息")
public class User {

    @Schema(name = "username", example = "tommy", required = true, description = "用户名")
    private String username;
    ...

}

第 7 步:@ApiResponses 和 @ApiResponse 注解

了解。

@ApiResponses@ApiResponse 注解组合使用,标注在 Controller 的方法上,用来指定 HTTP 响应。

@ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "OK", content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))),
        @ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Object.class))),
        @ApiResponse(responseCode = "500", description = "Internal Server Error", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Object.class)))
    })

第 8 步:验证

访问 http://127.0.0.1:8080/swagger-ui/index.html

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值