SpringBoot中怎么整合Swagger2
整合Swagger2在Spring Boot中是非常简单的,只需要以下几个步骤:
一、添加依赖库
二、配置Swagger2
三、编写API文档注释
一、添加依赖库
在pom.xml文件中添加Swagger2相关的依赖库,可以在Maven中央仓库搜索`swagger-spring-boot-starter`依赖,并添加对应的版本号。
<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>
二、配置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
三、编写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);
}
}
以上就是在Spring Boot中整合Swagger2的步骤。通过添加依赖库、配置Swagger2和编写API文档注释,就可以生成和展示Spring Boot中的API文档。在浏览器中输入`http://localhost:8080/swagger-ui.html`就可以访问API文档页面。
猜您想看
-
怎么在QQ上备份聊天记录?
一、QQ备份聊...
2023年05月15日 -
为什么SEO大神都不敢经常修改ktd三大标签
为什么SEO大...
2023年07月23日 -
hadoop如何自定义格式化输出
什么是Hado...
2023年05月26日 -
java怎么在给定的数组里面寻找重复数
寻找重复数是指...
2023年07月20日 -
大数据中怎么解决E50媒体无法更新的故障
一、检查网络环...
2023年05月26日 -
Python| Python的数字类型有哪些呢
Python的...
2023年07月23日