Swagger3

本文详细介绍了如何在SpringBoot项目中集成Swagger3,包括引入依赖、创建配置类、配置SwaggerAPI、使用@Api和@Operation注解、@Parameter处理参数、@Schema定义数据模型、以及@ApiResponses和@ApiResponse处理响应。最后指导如何访问SwaggerUI进行验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

### 使用 Swagger 3 的教程与文档 Swagger 是一种广泛使用的工具,用于设计、构建和记录 RESTful 接口。随着版本迭代,Swagger 3 提供了许多新特性和改进功能[^1]。 #### Maven 依赖配置 要集成 Swagger 3 到 Spring Boot 应用程序中,可以使用 `springdoc-openapi` 这一库替代传统的 `springfox-swagger`。以下是所需的 Maven 依赖项: ```xml <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.7.0</version> </dependency> ``` 此依赖会自动为应用程序提供 OpenAPI 文档以及交互式的 UI 页面[^4]。 #### 启动类配置 无需额外的复杂配置,在启动类上添加注解即可启用 Swagger 功能: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 默认情况下,访问地址为 `/v3/api-docs` 可获取 JSON 格式的 API 文档,而 `/swagger-ui/index.html` 或者简单地访问 `/swagger-ui/` 就能打开交互界面[^2]。 #### 自定义配置 (可选) 如果需要自定义标题、描述或其他元信息,可以通过创建一个 Java Bean 来实现: ```java import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OpenApiConfig { @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info() .title("Sample API Documentation") .description("This is a sample application using Swagger/OpenAPI.") .version("1.0")); } } ``` 以上代码片段展示了如何设置 API 文档的基本信息,比如名称、简介及其版本号等属性[^3]。 #### 官方资源链接 官方提供了详尽的技术资料帮助开发者更好地理解和运用该框架: - **GitHub Repository**: [https://github.com/springdoc/springdoc-openapi](https://github.com/springdoc/springdoc-openapi)[^4] - **Official Website**: [https://springdoc.org/](https://springdoc.org/) 这些网站不仅包含了详细的安装指南,还列举了一些实际案例来辅助学习过程。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值