Spring boot 2 集成接口工具swagger2

Published on with 276 views

上一篇讲到了mybatis-generator自动生成代码节省了很多重复工作,但是后台接口开发人员一般要花很多时间去写接口文档,接来下项目里面讲到集成swagger2接口自动生成的工具,可以节省很多写文档的时间。

第一步:引入需要的swagger2 jar包

一共需要两个jar包,一个核心包,一个ui界面jar包;swagger-ui-layer是github开源的美化界面的jar包,也可以不用引用;

<properties>
	<swagger2>2.9.2</swagger2>
</properties>
<!-- swagger 2 -->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>${swagger2}</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>${swagger2}</version>
</dependency>
<dependency>
	<groupId>com.github.caspar-chen</groupId>
	<artifactId>swagger-ui-layer</artifactId>
	<version>1.1.3</version>
</dependency><!-- swagger 2 -->

第二步:新增配置类SwaggerConfig.java

新增一个配置类,主要配置api接口页面显示信息及规则,下面先看看配置类信息;

/**

 * @Description swagger2
 * @Date 2019/2/21 18:31
 * @Created by gongxz
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    
     /**
      #在配置文件配置 swagger 相关路径
      swagger.version=1.0
      swagger.basePackage=com.springboot.controller     
    */
    @Value("${swagger.version}") private String version;
    @Value("${swagger.basePackage}") private String basePackage;

    @Bean
    public Docket createRestApi() {
        /*List<Parameter> operationParameters = new ArrayList<>();
        ParameterBuilder parameter = new ParameterBuilder();//参数
        parameter.name("name").defaultValue("user").description("姓名").required(true).parameterType("header")
        .modelRef(new ModelRef("string"));//todo
        operationParameters.add(parameter.build());*/
        return new Docket(DocumentationType.SWAGGER_2)
                //.groupName("api项目")//todo
                .apiInfo(apiInfo())
                //.genericModelSubstitutes(DeferredResult.class)//todo
                .useDefaultResponseMessages(false)//不使用默认的响应信息描述
                .globalResponseMessage(RequestMethod.GET,customerResponseMessage())//自定义全局的响应信息描述 获取
                .globalResponseMessage(RequestMethod.POST,customerResponseMessage())//自定义全局的响应信息描述 在服务器新建一个资源
                .globalResponseMessage(RequestMethod.DELETE,customerResponseMessage())//自定义全局的响应信息描述 删除
                .globalResponseMessage(RequestMethod.PUT,customerResponseMessage())//自定义全局的响应信息描述 在服务器更新资源(客户端提供完整资源数据)。
                .globalResponseMessage(RequestMethod.PATCH,customerResponseMessage())//自定义全局的响应信息描述 在服务器更新资源(客户端提供需要修改的资源数据)
                //.globalOperationParameters(operationParameters)//全局的参数说明,作用在所有方法上。
                //.forCodeGeneration(true)//todo
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))//需要显示的接口路径
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//这里采用包含注解的方式来确定要显示的接口
                .paths(PathSelectors.any())//todo
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("个人博客http://laog.net")//页面标题
                .description("个人博客http://laog.net")//描述
                .termsOfServiceUrl("http://laog.net")
                .version(version)//版本号
                .build();
    }

    /**
     * 自定义返回信息
     * @param
     * @return
     */
    private List<ResponseMessage> customerResponseMessage(){
        return ListUtils.ObjectConvertToList(
                new ResponseMessageBuilder()//500000
                        .code(Integer.valueOf(CodeMessage.Error.getCode()))
                        .message(CodeMessage.Error.getMsg())
                        //.responseModel(new ModelRef("Error"))
                        .build(),
                new ResponseMessageBuilder()//400001
                        .code(Integer.valueOf(CodeMessage.ParamError.getCode()))
                        .message(CodeMessage.ParamError.getMsg())
                        .build());
    }
}

useDefaultResponseMessages是否使用默认响应信息;最好自定义返回的响应错误码,所有我设置的为false;
globalResponseMessage配置全局的自定义的响应信息;

第三步:在controller控制器添加注解

/**

 * @Description 测试类

 * @Author gongxz
 * @Date 2019/2/14 15:04
 **/
@RestController
@Api(tags = "用户信息")
@RequestMapping(value = "/test")
public class TestController {

    @Autowired
    private TestService testService;

    //,,httpMethod = "path"
    @ApiOperation(value = "根据姓名和uuid获取用户信息", notes = "这是notes")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path",name = "name",value = "姓名",dataType = "String",required = true,defaultValue = "龚雄壮"),
            @ApiImplicitParam(paramType = "query",name = "uuid",value = "uuid",dataType = "String",required = true,defaultValue = "30f54356304811e9a2370235d2b38928")
    })
    @RequestMapping(value = "/user/name/{name}",method = RequestMethod.GET)
    public User findByNameAndUuid(@PathVariable("name") String name, HttpServletRequest request) {
        String uuid = request.getParameter("uuid");
        return testService.findByNameAndUuid(name,uuid);
    }

    @ApiOperation(value = "根据用户姓名获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "name",value = "姓名",dataType = "String",required = true,defaultValue = "龚雄壮")
    })
    @RequestMapping(value = "/user/name",method = RequestMethod.GET)
    public User findByName(@RequestParam("name") String name) {
        return testService.findByName(name);
    }

    @ApiOperation(value = "获得所有用户信息")
    @RequestMapping(value = "/users",method = RequestMethod.GET)
    public ResponseResult<PageList<User>> findAll() {
        PageList<User> pageListData = new PageList<>(testService.findAll());
        return new ResponseResult<>(pageListData);
    }

    @RequestMapping("/user/id/{id}")
    public User findById(@PathVariable("id") Long id) {
        return testService.findById(id);
    }

    @RequestMapping("/requestError")
    public String requestError() {
        return "requestError";
    }
}

@Api 作用在类上

  • tags 类的说明

@ApiOperation 作用在方法上

  • notes 标签
  • httpMethodhttp 请求方式“POST,GET....”

@ApiImplicitParams,@ApiImplicitParam 方法参数的说明

  • name:参数名
  • value:参数的汉字说明、解释
  • required:参数是否必须传
  • paramType:参数放在哪个地方
    · header --> 请求参数的获取:@RequestHeader
    · query --> 请求参数的获取:@RequestParam
    · path(用于restful接口)--> 请求参数的获取:@PathVariable
    · body(请求体)--> @RequestBody User user
    · form(不常用)
  • dataType:参数类型,默认String,其它值dataType="Integer"
  • defaultValue:参数的默认值

第四步:swagger 2 支持的返回结果嵌套层级显示ResponseResult<PageList<User>>

一般返回结果都会封装成通用的类,其中包含一个泛型参数,swagger2生成文档的时候也会显示泛型类里面的数据结构,先看效果图;
image.png
ResponseResult<PageList<User>>就从结构来看一共有三层,下面一层层来看具体封装类的结构

第一层:封装返回结果ResponseResult<T>类如下:

@ApiModel(value = "ResponseResult",description = "返回信息")

public class ResponseResult<T> {



    @ApiModelProperty(value = "返回编码",dataType = "String",name = "rspCode")
    private String rspCode ;
    @ApiModelProperty(value = "返回描述",dataType = "String",name = "rspMsg")
    private String rspMsg;
    @ApiModelProperty(value = "返回json数据对象",dataType = "Object",name = "data")
    private T data;

    public ResponseResult() {
        this(CodeMessage.Success.getCode(),CodeMessage.Success.getMsg());
    }

    public ResponseResult(String rspCode, String rspMsg) {
        this.rspCode = rspCode;
        this.rspMsg = rspMsg;
    }

    public ResponseResult(String rspCode, String rspMsg, T data) {
        this.rspCode = rspCode;
        this.rspMsg = rspMsg;
        this.data = data;
    }

    public ResponseResult(T data) {
        this.data = data;
    }

    public String getRspCode() {
        return rspCode;
    }

    public void setRspCode(String rspCode) {
        this.rspCode = rspCode;
    }

    public String getRspMsg() {
        return rspMsg;
    }

    public void setRspMsg(String rspMsg) {
        this.rspMsg = rspMsg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

第二层:封装分页数据对象PageList<T>类如下:

@ApiModel(value = "PageList",description = "分页对象")

public class PageList<T> implements Serializable {

    @ApiModelProperty(value = "页码",name = "currentPage",dataType = "int")
    private int currentPage = 1;

    @ApiModelProperty(value = "页面记录数",name = "pageSize",dataType = "int")
    private int pageSize = 1;

    @ApiModelProperty(value = "总页数",name = "totalPage",dataType = "int")
    private int totalPage = 10;

    @ApiModelProperty(value = "总记录数",name = "totalCount",dataType = "long")
    private long totalCount = 10;

    @ApiModelProperty(value = "分页数据",name = "list",dataType = "List")
    private List<T> list;

    public PageList() {
    }

    public PageList(List<T> list){
        this.list = list;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public long getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(long totalCount) {
        this.totalCount = totalCount;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }
}

第三层:具体的实体类:

@ApiModel(value="User",description = "用户实体")
public class User implements Serializable {

    @ApiModelProperty(value = "用户id",name = "id",dataType = "Long")
    private Long id;

    @ApiModelProperty(value = "用户姓名",name = "name",dataType = "String")
    private String name;

    @ApiModelProperty(value = "用户年龄",name = "age",dataType = "Integer")
    private Integer age;

    @ApiModelProperty(value = "uuid唯一主键",name = "uuid",dataType = "String")
    private String uuid;

    private static final long serialVersionUID = 1L;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid == null ? null : uuid.trim();
    }
}

第五步:运行Application

运行项目并访问http://localhost:8080/swagger-ui.html
如果引入了swagger-ui-layer也可以访问http://localhost:8080/docs.html

Responses