0%

Swagger介绍

Swagger介绍

由于现在很多都是前后端分离,前端、后端分别完成自己的工作,那么接口文档就是前后端的桥梁,使用swagger不仅可以作为一个接口调用工具,还可以作为一份接口文档

首先swagger的依赖为

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>

swagger的配置

swagger通过@EnableSwagger2来开启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
32
33
34
35
36
37
@Configuration
@EnableSwagger2
public class Swagger2 {

/**
* 创建API应用
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
// apiInfo() 增加API相关信息
.apiInfo(apiInfo())
.select()
// apis()设置扫描包或者注解
.apis(RequestHandlerSelectors.basePackage("xx.xx.xx.controllers"))
// paths()进行过滤,注册所需要的接口
.paths(PathSelectors.regex("/user.*"))
// groupName()进行分组
.groupName("用户管理")
.build();
}

/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://项目实际地址/swagger-ui.html
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("文档标题")
.description("文档描述")
.termsOfServiceUrl("http://localhost:8080/home")
.version("1.0")
.build();
}
}

注解

接口层面

在Controller类上可以使用@Api注解来对类进行说明

1
2
3
// tags用来说明类的作用,可以在UI中看到
@Api(tags = "jr单管理")
public class JrFormController

在api方法上可以使用@ApiOperation来说明接口的作用

1
2
3
4
5
6
7
8
// value:表示接口的作用,展示在接口列表;
//notes:进行接口备注说明,展示在接口的详情;
//tags:接口的标签,相同标签的接口会在一个标签页下展示,用来覆盖@Api的tags
@ApiOperation(value = "JR单撤销", notes = "v3.0.3")
@RequestMapping(value = "/cancel",method = RequestMethod.GET)
// 忽略该接口,UI上不做展示
@ApiIgnore
public String cancel(@ApiParam("jr单id") @RequestParam(value = "id") Long id)
  • @ApiImplicitParams:用在请求的方法上,表示一组参数说明
  • @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
    name:参数名称
    value:参数的汉字说明、解释
    required:参数是否必须传
    paramType: 参数放在哪个地方
    1.header --> 请求参数的获取:@RequestHeader
    2.query --> 请求参数的获取:@RequestParam
    3.path(用于restful接口)--> 请求参数的获取:@PathVariable
    4.body --> @RequestBody
    5.form --> @RequestPart
    dataType:参数类型,默认String,其它值dataType=”Integer”
    defaultValue:参数的默认值
  • @ApiResponses:用在请求的方法上,表示一组响应
  • @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
    code:数字,例如400
    message:信息,例如”请求参数没填好”
    response:返回的响应类型

数据传输对象层面

使用@ApiModel可以来对请求或响应对象进行标注,@ApiModelProperty对属性进行描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 对整个类的描述
// value:类的说明
// description:详细描述
@ApiModel("创意创建请求对象")
public class CreativeCreateReqData {
// 对具体字段的描述
// name:字段名称
// value:字段的说明
// required:是否必须
// example:示例值
@ApiModelProperty("请求token")
private String token;
private List<Creative> creatives;
}

欢迎关注我的其它发布渠道