Skip to content
On this page

简介

  • 由于架构革新,进入了前后端分离,服务端只需提供 RESTful API 的时代。
  • 而构建 RESTful API 会考虑到多终端的问题,这样就需要面对多个开发人员甚至多个开发团队。
  • 为了减少与其他团队对接的沟通成本,我们通常会写好对应的 API 接口文档。
  • 从最早开始的 word 文档,到后续的 showdoc,都能减少很多沟通成本,但随之带来的问题也比较麻烦。在开发期间接口会因业务的变更频繁而变动,如果需要实时更新接口文档,这是一个费时费力的工作。
  • 为了解决上面的问题,Swagger 应运而生。他可以轻松的整合进框架,并通过一系列注解生成强大的 API 文档。他既可以减轻编写文档的工作量,也可以保证文档的实时更新,将维护文档与修改代码融为一体,是目前较好的解决方案。

常用注解

  • @Api()用于类; 表示标识这个类是 swagger 的资源

  • @ApiOperation()用于方法; 表示一个 http 请求的操作 @ApiParam()用于方法,参数,字段说明; 表示对参数的添加元数据(说明或是否必填等)

  • @ApiModel()用于类 表示对类进行说明,用于参数用实体类接收

  • @ApiModelProperty()用于方法,字段 表示对 model 属性的说明或者数据操作更改

  • @ApiIgnore()用于类,方法,方法参数 表示这个方法或者类被忽略

  • @ApiImplicitParam() 用于方法 表示单独的请求参数

  • @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam

代码示例

@Api

java
@Api(value = "公告", tags = "公告接口")
public class NoticeController {

}

@ApiOperation

java
@GetMapping("/detail")
@ApiOperation(value = "获取公告详细信息", notes = "传入notice")
public R<Notice> detail(Integer id) {
   Notice detail = noticeService.getOne(id);
   return R.data(detail );公告
}

@ApiResponses

java
@GetMapping("/detail")
@ApiOperation(value = "获取公告详细信息", notes = "传入notice")
@ApiResponses(value = {@ApiResponse(code = 500, msg= "INTERNAL_SERVER_ERROR", response = R.class)})
public R<Notice> detail(Integer id) {
   Notice detail = noticeService.getOne(id);
   return R.data(detail );
}

@ApiImplicitParams

java
@GetMapping("/list")
@ApiImplicitParams({
   @ApiImplicitParam(name = "category", value = "公告类型", paramType = "query", dataType = "integer"),
   @ApiImplicitParam(name = "title", value = "公告标题", paramType = "query", dataType = "string")
})
@ApiOperation(value = "分页", notes = "传入notice")
public R<IPage<Notice>> list(@ApiIgnore @RequestParam Map<String, Object> notice, Query query) {
   IPage<Notice> pages = noticeService.page(Condition.getPage(query), Condition.getQueryWrapper(notice, Notice.class));
   return R.data(pages );
}

@ApiParam

java
@PostMapping("/remove")
@ApiOperation(value = "逻辑删除", notes = "传入notice")
public R remove(@ApiParam(value = "主键集合") @RequestBody @NotEmpty List<Integer> ids) {
   boolean temp = noticeService.delete(ids);
   return R.status(temp);
}

@ApiModel@ApiModelProperty

java
@Data
@ApiModel(value = "CbbUser ", description = "用户对象")
public class CbbUser implements Serializable {

   private static final long serialVersionUID = 1L;

   @ApiModelProperty(value = "主键", hidden = true)
   private Integer userId;

   @ApiModelProperty(value = "昵称")
   private String userName;

   @ApiModelProperty(value = "账号")
   private String account;

   @ApiModelProperty(value = "角色id")
   private String roleId;

   @ApiModelProperty(value = "角色名")
   private String roleName;

}

@ApiIgnore()

java
@ApiIgnore()
@GetMapping("/detail")
public R<Notice> detail(Integer id) {
   Notice detail = noticeService.getOne(id);
   return R.data(detail );
}