API ⽂档构建⼯具 - Swagger2
由于 Spring Boot 能够快速开发、便捷部署等特性,通常在使⽤ Spring Boot 构建 Restful 接⼝应⽤时考虑到多终端的原因,这些终端会共⽤很多底层业务逻辑,因此我们会抽象出这样⼀层来同时服务于多个移动端或者Web 前端。对于不同的终端公⽤⼀套接⼝ API 时,对于联调测试的时候就需要知道后端提供的接⼝ API列表⽂档,对于服务端开发⼈员来说就需要编写接⼝⽂档,描述接⼝的调⽤地址、参数结果等,这⾥借助第三⽅构建⼯具 Swagger2 来实现 API ⽂档⽣成功能。
1. 环境整合配置
pom.xml 依赖添加
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
配置类添加
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xxxx.springboot.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("⽤户管理接⼝API⽂档")
.version("1.0")
.build();
}
}
2. Swagger2 常⽤注解说明
2.1. @Api
@Api:⽤在请求的类上,说明该类的作⽤
tags="说明该类的作⽤"
@Api(tags="APP⽤户注册Controller")
2.2. @ApiOperation
@ApiOperation:"⽤在请求的⽅法上,说明⽅法的作⽤"
value="说明⽅法的作⽤"
notes="⽅法的备注说明"
@ApiOperation(value="⽤户注册",notes="⼿机号、密码都是必填项,年龄是选填项,但必须是数字")
2.3. @ApiImplicitParams
@ApiImplicitParams:⽤在请求的⽅法上,包含⼀组参数说明
@ApiImplicitParam:⽤在 @ApiImplicitParams 注解中,指定⼀个请求参数的配置信息
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地⽅
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(⽤于restful接⼝)--> 请求参数的获取:@PathVariable
· body(不常⽤)
· form(不常⽤)
dataType:参数类型,默认String,其它值dataType="Integer"
defaultValue:参数的默认值
@ApiImplicitParams({
@ApiImplicitParam(name="mobile",value="⼿机号",required=true,paramType="form"),
@ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
@ApiImplicitParam(name="age",value="年 龄",required=true,paramType="form",dataType="Integer")
})
.2.4. @ApiResponses
@ApiResponses:⽤于请求的⽅法上,表示⼀组响应
@ApiResponse:⽤在@ApiResponses中,⼀般⽤于表达⼀个错误的响应信息
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
@ApiOperation(value = "select请求", notes = "多个参数,多种的查询参数类型")
@ApiResponses({
@ApiResponse(code=400, message="请求参数没填好"),
@ApiResponse(code=404, message="请求路径没有或⻚⾯跳转路径不对")
})
2.5. @ApiModel
@ApiModel:⽤于响应类上,表示⼀个返回响应数据的信息
(这种⼀般⽤在post创建的时候,使⽤@RequestBody这样的场景,
请求参数⽆法使⽤@ApiImplicitParam注解进⾏描述的时候)
@ApiModelProperty:⽤在属性上,描述响应类的属性
@ApiModel(description= "返回响应数据")
public class RestMessage implements Serializable{
@ApiModelProperty(value = "是否成功")
private boolean success=true;
@ApiModelProperty(value = "返回对象")
private Object data;
@ApiModelProperty(value = "错误编号")
private Integer errCode;
@ApiModelProperty(value = "错误信息")
private String message;
/* getter/setter */
}
3. ⽤户模块注解配置
3.1. Controller 使⽤注解
@GetMapping("user/{userName}")
@ApiOperation(value = "根据⽤户名查询⽤户记录")
@ApiImplicitParam(name = "userName",value = "查询参数",required = true,paramType =
"path")
public User queryUserByUserName(@PathVariable String userName){
return userService.queryUserByUserName(userName);
}
@ApiOperation(value = "根据⽤户id查询⽤户记录")
@ApiImplicitParam(name = "userId",value = "查询参数",required = true,paramType =
"path")
@GetMapping("user/id/{userId}")
public User queryUserByUserId(@PathVariable Integer userId, HttpServletRequest
request){
return userService.queryUserByUserId(userId);
}
@GetMapping("user/list")
@ApiOperation(value = "多条件查询⽤户列表记录")
public PageInfo<User> list(UserQuery userQuery){
return userService.queryUserByParams(userQuery);
}
@PutMapping("user")
@ApiOperation(value = "⽤户添加")
@ApiImplicitParam(name = "user",value = "⽤户实体类",dataType = "User")
public ResultInfo saveUser(@RequestBody User user){
ResultInfo resultInfo=new ResultInfo();
try {
userService.saveUser(user);
} catch (ParamsException e) {
e.printStackTrace();
resultInfo.setCode(e.getCode());
resultInfo.setMsg(e.getMsg());
(Exception e) {
e.printStackTrace();
resultInfo.setCode(300);
resultInfo.setMsg("记录添加失败!");
}
return resultInfo;
}
@PostMapping("user")
@ApiOperation(value = "⽤户更新")
@ApiImplicitParam(name = "user",value = "⽤户实体类",dataType = "User")
public ResultInfo updateUser(@RequestBody User user){
ResultInfo resultInfo=new ResultInfo();
try {
userService.updateUser(user);
} catch (ParamsException e) {
e.printStackTrace();
resultInfo.setCode(e.getCode());
resultInfo.setMsg(e.getMsg());
}catch (Exception e) {
e.printStackTrace();
resultInfo.setCode(300);
resultInfo.setMsg("记录更新失败!");
}
return resultInfo;
}
@PutMapping("user/{userId}")
@ApiOperation(value = "根据⽤户id删除⽤户记录")
@ApiImplicitParam(name = "userId",value = "查询参数",required = true,paramType =
"path")
public ResultInfo deleteUser(@PathVariable Integer userId){
ResultInfo resultInfo=new ResultInfo();
try {
userService.deleteUser(userId);
} catch (ParamsException e) {
e.printStackTrace();
resultInfo.setCode(e.getCode());
resultInfo.setMsg(e.getMsg());
}catch (Exception e) {
e.printStackTrace();
resultInfo.setCode(300);
resultInfo.setMsg("记录删除失败!");
}
return resultInfo;
}
3.2. JavaBean 使⽤注解
- User.java
@ApiModel(description = "响应结果-⽤户信息")
public class User {
@ApiModelProperty(value = "⽤户id",example = "0")
private Integer id;
@ApiModelProperty(value = "⽤户名")
private String userName;
@ApiModelProperty(value = "⽤户密码")
private String userPwd;
/*
省略get|set
*/
}
- UserQuery.java
@ApiModel(description = "⽤户模块条件查询类")
public class UserQuery {
@ApiModelProperty(value = "分⻚⻚码",example = "1")
private Integer pageNum = 1;
@ApiModelProperty(value = "每⻚⼤⼩",example = "10")
private Integer pageSize = 10;
@ApiModelProperty(value = "⽤户名")
private String userName;
/*
省略get|set
*/
}
- ResultInfo.java
@ApiModel(description = "响应结果 - Model信息")
public class ResultInfo {
@ApiModelProperty(value = "响应状态码",example = "200")
private Integer code=200;
@ApiModelProperty(value = "响应消息结果")
private String msg = "success";
@ApiModelProperty(value = "响应具体结果信息")
private Object result;
/*
省略get|set
*/
}
4. Swagger2 接⼝⽂档访问
启动⼯程,浏览器访问 :http://localhost:8080/springboot_mybatis/swagger-ui.html