SpringBoot项目集成Swagger2

zhangdy0 2020-05-19

一、前言

现如今,前后端分离已经逐渐成为互联网项目一种标准的开发方式,前端与后端交给不同的人员开发,

但是项目开发中的沟通成本也随之升高,这部分沟通成本主要在于前端开发人员与后端开发人员对WebAPI接口的沟通,Swagger2 就可以很好地解决,它可以动态生成Api接口文档,降低沟通成本,促进项目高效开发。

下面就来说一下Swagger2的使用。

1.1、引入对应到jar包

在build.gradle文件中添加swagger2的包,引入相关的依赖,pom文件类似,见下图

compile ‘io.springfox:springfox-swagger2:2.9.2‘compile ‘io.springfox:springfox-swagger-ui:2.9.2‘compile "io.springfox:springfox-bean-validators:2.9.2"

SpringBoot项目集成Swagger2

1.2、swagger2的配置文件

@Configuration
@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .useDefaultResponseMessages(false) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("利用swagger构建api文档") .description("简单使用swagger2") .version("1.0") .build(); } }

二、swagger的基础注解介绍

swagger通过注解生成接口文档,包括接口名、请求方法、参数、返回信息的等等。

  • @Api:修饰整个类,描述Controller的作用
  • @ApiOperation:描述一个类的一个方法,或者说一个接口
  • @ApiParam:单个参数描述
  • @ApiModel:用对象实体来作为入参
  • @ApiProperty:用对象接实体收参数时,描述对象的一个字段
  • @ApiResponse:HTTP响应其中1个描述
  • @ApiResponses:HTTP响应整体描述
  • @ApiIgnore:使用该注解忽略这个API
  • @ApiError :发生错误返回的信息
  • @ApiImplicitParam:一个请求参数
  • @ApiImplicitParams: 多个请求参数

2.1、@Api作用于Controller   @ApiModel标明这个类是入参

2.2、@ApiOperation

用于描述一个方法或者接口

可以添加的参数形式:@ApiOperation(value = “接口说明”, httpMethod = “接口请求方式”, response = “接口返回参数类型”, notes = “接口发布说明”)

2.3、@ApiParam单个参数描述

@ApiParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”,dateType="变量类型”,paramType="请求方式”)

2.4、@ApiImplicitParam 一个请求参数

@ApiImplicitParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”,dateType="变量类型”,paramType="请求方式”)

@ApiOperation(value = "根据用户名获取用户的信息",notes = "查询数据库中的记录",httpMethod = "POST",response = String.class)
@ApiImplicitParam(name = "userName",value = "用户名",required = true,dataType = "String",paramType = "query")

2.5、@ApiImplicitParams 多个请求参数

参数和@ApiImplicitParam一致,只是这个注解可以添加多个参数而已

@ApiImplicitParams({
            @ApiImplicitParam(name = "nickName",value = "用户的昵称",paramType = "query",dataType = "String",required = true),
            @ApiImplicitParam(name = "id",value = "用户的ID",paramType = "query",dataType = "Integer",required = true)
    })
    public String getUserInfoByNickName(String nickName, Integer id) {
        return "1234";
    }

其余的都类似。

整个controller的代码如下

@RestController@RequestMapping("/swagger")@Api(value = "swagger2的demo例子")public class SwaggerController {    @RequestMapping("/swagger")    @ResponseBody    @ApiOperation(value = "根据用户名获取用户的信息",notes = "查询数据库中的记录",httpMethod = "POST",response = String.class)    @ApiImplicitParam(name = "userName",value = "用户名",required = true,dataType = "String",paramType = "query")    public String getUserInfo(String userName) {        return "1234";    }    @RequestMapping(value = "/getuserinfobynickname",method = {RequestMethod.GET,RequestMethod.POST})    @ResponseBody    @ApiOperation(value = "根据用户昵称获取用户信息",notes = "查询数据库中的记录")    @ApiImplicitParams({            @ApiImplicitParam(name = "nickName",value = "用户的昵称",paramType = "query",dataType = "String",required = true),            @ApiImplicitParam(name = "id",value = "用户的ID",paramType = "query",dataType = "Integer",required = true)    })    public String getUserInfoByNickName(String nickName, Integer id) {        return "1234";    }    @RequestMapping(value = "/getuserinfobyid",method = {RequestMethod.GET,RequestMethod.POST})    @ResponseBody    @ApiOperation(value = "根据用户id获取用户信息",notes = "查询数据库中的记录",httpMethod = "POST")    public String getUserInfoById(@ApiParam(name = "nickName",value = "用户的昵称",required = true,defaultValue = "123-默认值")                                          String nickName,@ApiParam(name = "id",value = "用户ID",required = true) Integer id) {        return "1234";    }    @RequestMapping(value = "/userregister",method = {RequestMethod.GET,RequestMethod.POST})    @ResponseBody    @ApiOperation(value = "register",notes = "注册的实体类")    public Register userRegister(Register register) {        return register;    }}

相对应的接口文档如下:

SpringBoot项目集成Swagger2

可以直接进行测试

SpringBoot项目集成Swagger2

 SpringBoot项目集成Swagger2

对应的实体说明:

@ApiModel(value = "用户注册的实体")
public class Register {
    @ApiModelProperty(name = "userName",notes = "用户名",dataType = "String",required = true)
    private String userName;

    @ApiModelProperty(name = "nickName",notes = "用户昵称",dataType = "String",required = true)
    private String nickName;

    @ApiModelProperty(name = "age",notes = "用户年龄",dataType = "int",required = true)
    private int age;
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Register{" +
                "userName=‘" + userName + ‘\‘‘ +
                ", nickName=‘" + nickName + ‘\‘‘ +
                ", age=" + age +
                ‘}‘;
    }
}

补充说明点:

Swagger2的相关注解只是展示给前端看,不具备校验的功能,不能把它跟hibernate.validation相关的注解类比。

@ApiModelProperty 里面也有required,hidden,allowableValues等属性

校验方面,@NotNull @NotBlank,@NotEmpty  @Size(min=1,max=100) @Min(1),@Max(100)等

相关推荐