Spring boot 集成swagger

Spring boot 集成swagger

以整合mysql为例 mysql,mybatis

添加依赖

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

swagger 注解

@Api 类

  1. value
  2. tags 标签
  3. description 描述

@ApiParam request 参数

  1. name
  2. value (有时也做参数描述)
  3. defaultValue 默认值
  4. allowableValues 设置默认值, 多个值 逗号<,> 分隔 (类似选择框),好像支持 range[1,8]
  5. required 设置是否必填

@ApiModelProperty response 参数

  1. name
  2. value (有时也做参数描述)
  3. defaultValue 默认值
  4. allowableValues 设置默认值, 多个值 逗号<,> 分隔 (类似选择框)
  5. dataType 数据类型
  6. notes 参数描述

示例代码

controller

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
@RestController
@Api(tags = {"user"}, description = "用户操作方法 ")
public class UserController {
@Autowired
private UserService userService;
/**
* 添加用户
*
* @param user
* @return
*/
@ApiOperation(value = "添加用户 ", notes = "大大")
@ApiResponses({
@ApiResponse(code =200, message ="请求成功" ),
@ApiResponse(code =404, message ="文件页面找不到" )
})
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户id", dataType = "Long",paramType = "path"),
@ApiImplicitParam(name = "user", value = "用户信息", dataType = "User",paramType = "body")}
)
@RequestMapping(value = "/user/{id}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public User addUser(@PathVariable Long id,@RequestBody User user) {
return userService.addUser(user);
}
@ApiOperation(value = "获取用户列表" )
@ApiImplicitParam
@RequestMapping(value = "/getUser", method = RequestMethod.GET )
public List<User> getUser(UserCondition condition) {
return null;
}
}

entity

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
38
39
40
41
42
@Data
@ApiModel
public class User implements Serializable {
/**
* 组件
*/
@ApiParam(value = "用户主键")
@ApiModelProperty(value = "用户主键")
private Long id;
/**
* 用户名
*/
private String userName;
/**
* 密码
*/
private String passWord;
/**
* 创建时间
*/
@ApiParam(value = "创建时间 (时间格式;yyyy-MM-dd)", example = "2016-02-12")
@ApiModelProperty(notes = "创建时间 (时间格式;yyyy-MM-dd)", example = "2016-02-12", dataType = "string")
private Date createDate;
/**
* 年龄
*/
@ApiParam(value = "年龄", allowableValues = "range[1, 5]")
private Byte age;
/**
* 性别
*/
@ApiParam(value = "性别", allowableValues = "男,女,人妖")
private String sex;
/**
* 描述s
*/
@ApiParam(value = "描述", allowableValues = "range[1, 5]")
private String description;

参考文档

  1. swagger-core wiki
  2. springfox-swagger2
  3. Spring Boot中使用Swagger2构建强大的RESTful API文档
分享到 评论