整合 Swagger2 在 Spring Boot 中是非常简单的,只需要以下几个步骤:
一、添加依赖库
二、配置 Swagger2
三、编写 API 文档注释

一、添加依赖库
在 pom.xml 文件中添加 Swagger2 相关的依赖库,可以在 Maven 中央仓库搜索 swagr-sprg-bt-ter 依赖,并添加对应的版本号。

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.9.2</version>
</dependency>
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.9.2</version>
</dependency>
XML

二、配置 Swagger2
在 Spring Boot 的配置文件中加入 Swagger2 相关的配置,配置包括启用 Swagger2 以及配置接口文档的基本信息。

# 启用Swagger2
swagger.enabled=true
# API文档标题
swagger.title=Spring Boot中使用Swagger2
# API文档描述
swagger.description=Swagger2用于生成和展示Spring Boot中的API文档
# API文档版本
swagger.version=1.0.0
# API文档许可证
swagger.license=Apache License 2.0
.properties

三、编写 API 文档注释
在 Spring Boot 的 Controller 类或者 Controller 的方法上,使用 Swagger2 的注解来编写 API 文档注释。常用的 Swagger2 注解包括 Api、ApiOperation、ApiParam 等,用于描述接口的基本信息、接口的具体操作以及接口参数的描述。

示例代码如下:

import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(tags = "用户管理")
@RequestMapping("/users")
public class UserController {

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path", dataType = "int")
    public User getUserById(@PathVariable int id) {
        // 获取用户逻辑
        return userService.getUserById(id);
    }

    @PostMapping("/")
    @ApiOperation("创建用户")
    public User createUser(@RequestBody @ApiParam("用户信息") User user) {
        // 创建用户逻辑
        return userService.createUser(user);
    }
}
Java

以上就是在 Spring Boot 中整合 Swagger2 的步骤。通过添加依赖库、配置 Swagger2 和编写 API 文档注释,就可以生成和展示 Spring Boot 中的 API 文档。在浏览器中输入 hp:/localhost:8080swagr-ui.html 就可以访问 API 文档页面。