1.Swagger

注意的点:接口文档只能在测试/开发环境开启,其他环境请关闭。

常用的Swagger注解

  • @Api 用于Controller
  • @ApiOperation 用于Controller内的方法。
  • @ApiResponses 用于标识接口返回数据的类型。
  • @ApiModel 用于标识类的名称
  • @ApiModelProperty 用于标识属性的名称

添加依赖

<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>

2.常用的封装

统一返回 ResultVo
将所有的接口的响应数据的格式进行统一。

@Data
@ApiModel("固定返回格式")
public class ResultVo {
    
    @ApiModelProperty("错误码")
    private Integer code;

    
    @ApiModelProperty("提示信息")
    private String message;

    
    @ApiModelProperty("响应数据")
    private Object data;

}

抽象表单 BaseForm

public abstract class BaseForm<T> {
    
    public abstract T buildEntity();

}

用法

@Override
public boolean addUser(AddUserForm userForm) {
        User user = new User();
        user.setNickname(userForm.getNickname());
        user.setBirthday(userForm.getBirthday());
        user.setUsername(userForm.getUsername());
        user.setPassword(userForm.getPassword());
        return save(user);
    }

3.通用的分页对象

PageForm

@Data
@ApiModel(value = "分页数据", description = "分页需要的表单数据")
public class PageForm<T extends PageForm<?>>{
    
    @ApiModelProperty(value = "页码 从第一页开始 1")
    @Min(value = 1, message = "页码输入有误")
    private Integer current;

    
    @ApiModelProperty(value = "每页显示的数量 范围在1~100")
    @Range(min = 1, max = 100, message = "每页显示的数量输入有误")
    private Integer size;

    
    @ApiModelProperty(hidden = true)
    public T calcCurrent(){
        current = (current - 1 ) * size;
        return (T) this;
    }
}

PageVo

@Data
public class PageVo<T> {
    @ApiModelProperty(value = "分页数据")
    private List<T> records;
    @ApiModelProperty(value = "总条数")
    private Integer total;
    @ApiModelProperty(value = "总页数")
    private Integer pages;
    @ApiModelProperty(value = "当前页")
    private Integer current;
    @ApiModelProperty(value = "查询数量")
    private Integer size;
    @ApiModelProperty(hidden = true)
    public PageVo<T> setCurrentAndSize(PageForm<?> pageForm){
        BeanUtils.copyProperties(pageForm,this);
        return this;
    }
    @ApiModelProperty(hidden = true)
    public void setTotal(Integer total) {
        this.total = total;
        this.setPages(this.total % this.size > 0 ? this.total / this.size + 1 : this.total / this.size);
    }
}

ListUserForm

@Data
@ApiModel("获取用户列表需要的表单数据")
@EqualsAndHashCode(callSuper = false)
public class ListUserForm extends PageForm<ListUserForm> {
    
    @ApiModelProperty("用户状态")
    @NotEmpty(message = "用户状态不能为空")
    @Range(min = -1 , max = 1 , message = "用户状态有误")
    private String status;

}

Q.E.D.