由于 Spring Boot 能够快速开发、便捷部署等特性,通常在使用 Spring Boot 构建 Restful 接口应用时考虑到多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者 Web 前端。对于不同的终端公用一套接口 API 时,对于联调测试的时候就需要知道后端提供的接口 API 列表文档,对于服务端开发人员来说就需要编写接口文档,描述接口的调用地址、参数结果等,这里借助第三方构建工具 Swagger2 来实现 API 文档生成功能
环境整合配置
<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>
配置类添加
package com.xxx.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("用户管理接口API文档")
.version("1.0")
.build();
}
}
Swagger2 常用注解说明
@Api :用在请求的类上,说明该类的作用tags = " 说明该类的作用 "@Api ( tags = "APP 用户注册 Controller" )@ApiOperation : " 用在请求的方法上,说明方法的作用 "value = " 说明方法的作用 "notes = " 方法的备注说明 "@ApiOperation ( value = " 用户注册 " , notes = " 手机号、密码都是必填项,年龄是选填项,但必须是数字 " )@ApiImplicitParams :用在请求的方法上,包含一组参数说明@ApiImplicitParam :用在 @ApiImplicitParams 注解中,指定一个请求参数的配置信息name :参数名value :参数的汉字说明、解释required :参数是否必须传paramType :参数放在哪个地方· header --> 请求参数的获取: @RequestHeader· query --> 请求参数的获取: @RequestParam· path (用于 restful 接口) --> 请求参数的获取: @PathVariable· body (不常用)· form (不常用)dataType :参数类型,默认 String ,其它值 dataType = "Integer"defaultValue :参数的默认值@ApiResponses3.2.5. @ApiModel3.3. 用户模块注解配置3.3.1. Controller 使用注解@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" )}@ApiResponses3.2.5. @ApiModel3.3. 用户模块注解配置3.3.1. Controller 使用注解@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" )})@ApiResponses :用于请求的方法上,表示一组响应@ApiResponse :用在 @ApiResponses 中,一般用于表达一个错误的响应信息code :数字,例如 400message :信息,例如 " 请求参数没填好 "response :抛出异常的类@ApiOperation ( value = "select 请求 " , notes = " 多个参数,多种的查询参数类型 " )@ApiResponses ({@ApiResponse ( code = 400 , message = " 请求参数没填好 " ),@ApiResponse ( code = 404 , message = " 请求路径没有或页面跳转路径不对 " )})@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 */}
接下来是具体实例:
package com.xxx.po;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* @Author 陈平安
* @Date 2022/6/30 9:40
* @PackageName:com.xxx.po
* @ClassName: User
* @Description: TODO
* @Version 1.0
*/
@ApiModel(description = "用户实体类")
public class User {
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
@ApiModelProperty(value = "用户id" ,example = "0")
private Integer userId;
@ApiModelProperty(value = "用户name" ,example = "null")
private String userName;
private String userPwd;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
}
package com.xxx.query;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(description = "用户模块条件查询类")
public class UserQuery {
@ApiModelProperty(value = "分页页码",example = "1")
private Integer pageNum = 1; // 当前页
@ApiModelProperty(value = "每页大小",example = "10")
private Integer pageSize = 3; // 每页显示的数量
@ApiModelProperty(value = "用户名")
private String userName; // 查询条件:用户名
public UserQuery() {
}
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "UserQuery{" +
"pageNum=" + pageNum +
", pageSize=" + pageSize +
", userName='" + userName + '\'' +
'}';
}
}
package com.xxx.controller;
import com.github.pagehelper.PageInfo;
import com.xxx.Excelption.ParamsException;
import com.xxx.po.User;
import com.xxx.query.UserQuery;
import com.xxx.service.UserService;
import com.xxx.vo.ResultInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* @Author 陈平安
* @Date 2022/6/30 9:49
* @PackageName:com.xxx.controller
* @ClassName: UserController
* @Description: TODO
* @Version 1.0
*/
@Api(tags = "用户模块")
@RestController
public class UserController {
@Resource
private UserService userService;
@ApiOperation(value = "根据用户名查询对象")
@ApiImplicitParam(name = "UserName" ,value = "用户名称",required = true,paramType = "path")
@ApiResponse(code = 404,message = "资源未找到")
/*** 用户查询用户 * @param user * @return */
@GetMapping("/user/{userName}")
public User queryUserByUserName(@PathVariable String userName) {
System.out.println("***********" + userName);
System.out.println("+++++++++++" + userName + "-------");
return userService.queryUserByUserName(userName);
}
/*** 查询用户 * @param user * @return */
@ApiOperation(value = "查询用户")
@ApiImplicitParam(name = "userId" ,value = "用户id",required = true,paramType = "path")
@GetMapping("/user01/{id}")
public User queryById(@PathVariable Integer id) {
return userService.queryById(id
);
}
/*** 添加用户 * @param user * @return */
@ApiOperation(value = "添加用户")
@ApiImplicitParam(name = "user" ,value = "用户")
@PutMapping("/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());
} catch (Exception e) {
e.printStackTrace();
resultInfo.setCode(300);
resultInfo.setMsg("记录添加失败!");
}
return resultInfo;
} /*** 修改用户 * @param user * @return */
@ApiOperation(value = "修改用户")
@ApiImplicitParam(name = "user" ,value = "用户",required = true,paramType = "path")
@PostMapping("/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;
} /*** 删除用户 * @param userId * @return */
@ApiOperation(value = "删除用户")
@ApiImplicitParam(name = "UserId" ,value = "用户id")
@DeleteMapping("/user/{userId}")
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());
// 2.2 .5.分页条件查询操作
// 2.2 .5 .1.UserQuery
} catch (Exception e) {
e.printStackTrace();
resultInfo.setCode(300);
resultInfo.setMsg("记录删除失败!");
}
return resultInfo;
}
@ApiOperation(value = "通过指定参数,分页查询用户列表")
/*** * @param userQuery * @return */
@GetMapping("user/list")
public PageInfo<User> list(UserQuery userQuery) {
return userService.queryUserByParams(userQuery);
}
}