Contents
  1. 1. Springboot 与Swagger2集成

Springboot 与Swagger2集成

现在swagger2 作为微服务应用中必不可少的一种集成插件了,可以避免去写接口文档的时间和麻烦,项目开发过程中接口开发完了就可以直接部署了,在线文档还可以直接测试。废话不多说,上干货。

1.1 引入相关的依赖配置

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>

1.2 构建配置类信息

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
// 注解表示配置类
@Configuration
//注解开启Swagger2
@EnableSwagger2
public class Swagger2 {

/**
* 通过 createRestApi函数来构建一个DocketBean
* 函数名,可以随意命名,喜欢什么命名就什么命名
*/
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("top.xjp89.demo"))
.paths(PathSelectors.any())
.build();
}

private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title(" 后台接口")
.version("2.0")
.description("项目重构")
.contact(new Contact("jammy","","645646828@qq.com"))
.build();
}
}

1.3 在哪里用

1)java 的model 类中

1
2
3
4
5
6
7
8
9
@ApiModel(value="XX",description="演示")
public class DemoEntity{


@ApiModelProperty(value="用户名",require="true") // 还有更多属性自己体会
private String userName;
...

}

2)rest接口

1
2
3
4
5
6
7
8
9
10
@RestController
@Api(tags={"用户管理"})
public class UserController{

@DeleteMapping(value="delete/{id}")
@ApiOperation(value="删除用户")
@ApiImplicitParam(name="id",value="主键id",required=true)
public void delete(@PathVariable Long id)

}

1.4Swagger2 注解

注解 用处 功能说明 参数
@Api() 用于类 表示这个类是swagger 资源 tags-表示说明
value 也是说明,可以使用tags进行代替
@ApiOperation() 用于方法 表示一个http请求的操作 value用于方法描述
notes:提示内容
tags:可以重新分组
@ApiParam() 用于方法,参数,字段说明 表示对参数的添加元数据(说明是否必填等) name:参数名
value:参数说明
required:是否必须
@ApiModel() 用于类 表示对类进行说明,用于参数用实体类接收 value:表示对象名
description:描述
@ApiModelProperty() 用于方法,字段 表示对model属性的说明或者数据操作更改 value:字段说明
name:重写属性名字
dataType:重写属性类型
required:是否必须
example:举例说明
hidden:隐藏
@ApiIgnore() 用于类,方法,方法参数 表示这个方法或者类被忽略
@ApiImplicitParam() 用于方法 表示单独的请求参数
@ApiImplicitParams() 用于方法 包含多个@ApiImplicitParam name:参数名
value:参数说明
dataType:数据类型
paramType:参数放在哪个地方header–>请求参数的获取@RequestHeader;query–>请求参数的获取@RequestParam;path –> @PathVariable;body–>@RequestBody;form–>普通表单提交
example:举例说明
Contents
  1. 1. Springboot 与Swagger2集成