Spring Boot集成 Swagger2 展现在线接口文档
1. Swagger 简介
随着互联网技术的发展,现在的网站架构基本都由原来的后端渲染,变成了前后端分离的形态,而且前端技术和后端技术在各自的道路上越走越远。前端和后端的唯一联系,变成了 API 接口,所以 API 文档变成了前后端开发人员联系的纽带,变得越来越重要。
那么问题来了,随着代码的不断更新,开发人员在开发新的接口或者更新旧的接口后,由于开发任务的繁重,往往文档很难持续跟着更新,Swagger 就是用来解决该问题的一款重要的工具,对使用接口的人来说,开发人员不需要给他们提供文档,只要告诉他们一个 Swagger 地址,即可展示在线的 API 接口文档,除此之外,调用接口的人员还可以在线测试接口数据,同样地,开发人员在开发接口时,同样也可以利用 Swagger 在线接口文档测试接口数据,这给开发人员提供了便利。
官方对 Swagger 的定义为:
The Best APIs are Built with Swagger Tools
翻译成中文是:“最好的 API 是使用 Swagger 工具构建的”。由此可见,Swagger 官方对其功能和所处的地位非常自信,由于其非常好用,所以官方对其定位也合情合理。如下图所示:
2.Swagger2依赖
使用 Swagger2 工具,必须要导入 maven 依赖,当前官方最高版本是 2.8.0,当前我们实际项目中使用的是 2.2.2 版本,该版本稳定,界面友好,所以本节课主要围绕着 2.2.2 版本来展开,依赖如下:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
3.Swagger2 的配置
使用 Swagger2 需要进行配置,Spring Boot 中对 Swagger2 的配置非常方便,新建一个配置类,Swagger2 的配置类上除了添加必要的@Configuration 注解外,还需要添加 @EnableSwagger2 注解。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
// 指定构建api文档的详细信息的方法:apiInfo()
.apiInfo(apiInfo()) .select()
// 指定要生成api接口的包路径,这里把controller作为包路径,生成controller 中的所有接口
.apis(RequestHandlerSelectors.basePackage("com.springboot.demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 设置页面标题
.title("Spring Boot集成Swagger2接口总览")
// 设置接口描述
.description("Spring Boot集成Swagger2学习")
// 设置联系方式
.contact("CodersCoder" + "优快云:https://blog.youkuaiyun.com/CodersCoder")
// 设置版本
.version("1.0")
// 构建
.build();
}
}
4.Swagger2 的使用
绍 Swagger2 中的几个常用的注解,分别在实体类上,Controller 类上以及 Controller 中的方法上。
4.1实体类注解
@ApiModel 和 @ApiModelProperty 注 解:
@ApiModel 注解用于实体类,表示对类进行说明,用于参数用实体类接收。
@ApiModelProperty 注解用于类中属性,表示对 model 属性的说明或者数据操作更改。
@ApiModel(value = "用户实体类")
public class User {
@ApiModelProperty(value = "用户唯一标识")
private Long id;
@ApiModelProperty(value = "用户姓名")
private String username;
@ApiModelProperty(value = "用户密码")
private String password;
// 省略set和get方法
}
4.2Controller 类中相关注解
@Api 、 @ApiOperation 和 @ApiParam 注解:
@Api 注解用于类上,表示标识这个类是 swagger 的资源。 @ApiOperation 注解用于方法,表示一个 http 请求的操作。 @ApiParam 注解用于参数上,用来标明参数信息。
@RestController
@RequestMapping("/swagger")
@Api(value = "Swagger2 在线接口文档")
public class TestController {
@GetMapping("/get/{id}")
@ApiOperation(value = "根据用户唯一标识获取用户信息")
public JsonResult<User> getUserInfo(@PathVariable @ApiParam(value = "用户唯一 标识") Long id) {
// 模拟数据库中根据id获取User信息
User user = new User(id, "coders", "123456");
return new JsonResult(user);
}
}