Swagger2

简介


API 一定要开发文档配合,移动端只需要根据开发文档进行开发。
传统开发文档的问题:格式随意,更新不及时

Swagger 的目标是为 REST APIS 定义一个标准的,与语言无关的接口。使人和计算机在看不到源码或者看不到文档情况下理解各种服务的功能。

简单说, swagger 能够根据代码中的注解,自动生成 api 文档,并提供测试接口。

swagger 和 swagger2 是两个不同版本,swagger2 也叫 springfox,就是 swagger-springmvc 的升级版。

使用:


添加依赖

1
2
3
4
5
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>

在 api 中插入配置类

SwaggerConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* 把一个 Docker 交给 Spring 管理
* Docker: Springfox 提供的文档配置对象
*
*/
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select().build();
}
}

访问 域名:端口号/swagger-ui.html 访问开发文档

swagger2 的常用注解


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* @Api: 用在类上,说明该类的作用
* @Api(value = "用户资源", description = "用户资源控制器")
* @ApiOperation 用在方法上,说明方法的作用
* @ApiOperation(value = "注册功能", notes = "其实就是新增用户")
*/

// 描述方法参数文档
@ApiImplictParam({
@ApiImplictParam(value = "昵称", name = "nickName", dataType = "String", required = true)
@ApiImplictParam(value = "邮箱", name = "email", dataType = "String", required = true)
})

// 在 domain 中配置的注解标注 javabean 类中哪些是必须或者非必须字段
// 这种一般用在 post 创建的时候,使用 @RequestBody 这样的场景,
// 请求参数无法使用 @ApiImplicitParam 注解进行描述的时候
@ApiModel(description = "游记")

// 描述一个 model 的属性
@APIModelProperty(value = "标题", name = "title", dataType = "String", required = true)

// 贴在 API 方法上,表示返回的状态码和 对应的message
// 针对响应的描述
@ApiResponse({
@ApiResponse(code = 200, message = "用户注册成功"),
@ApiResponse(code = 401, message = "没有登录"),
})

// 不想让某个类暴露在文档时使用 贴在类上
@ApiIgnore
public class UserController

Models 可以看到所有的模型对象。

文章作者: Ammar
文章链接: http://lizhaoloveit.cn/2019/09/16/Swagger2/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Ammar's Blog
打赏
  • 微信
  • 支付宝

评论