SpringBoot使用swagger2生成RESTful风格的接口文档(22)

简介

现如今,前后端分离已经逐渐成为互联网项目一种标准的开发方式,前端与后端交给不同的人员开发,
但是项目开发中的沟通成本也随之升高,这部分沟通成本主要在于前端开发人员与后端开发人员对WebAPI接口的沟通,Swagger2 就可以很好地解决,它可以动态生成Api接口文档,降低沟通成本,促进项目高效开发。

pom.xml引入相关依赖

 <properties>
        <swagger.version>2.9.2</swagger.version>
 </properties>
    
 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>
 </dependencies>    

swagger配置

application.yml配置文件

#生产环境改成false禁用
server:
 port: 8017
swagger:
  enable: true

swagger配置类

@ConditionalOnProperty 注解用于动态加载配置类
通过其两个属性name以及havingValue来实现的,其中name用来从application.properties中读取某个属性值。
如果该值为空,则返回false;
如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。
如果返回值为false,则该configuration不生效(不会加载该类);为true则生效。

@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class SwaggerConfig {

    /**
     * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
     * @return Docket
     */
    @Bean(value = "defaultApi")
    public Docket defaultApi() {
        //添加header参数
        ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        ticketPar.name("token")
                .description("用户登录获取的token信息")
                .modelRef(new ModelRef("string")).parameterType("header")
                //header中的参数是非必填的。
                .required(false).build();
        pars.add(ticketPar.build());
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                // 为当前包路径
	                .apis(RequestHandlerSelectors.basePackage("com.ljm.boot.swagger"))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .groupName("需要token验证")
                .globalOperationParameters(pars);
    }


    /**
     * api文档的详细信息函数,注意这里的注解引用的是哪个
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // //大标题
                .title("【SpringBoot框架篇】 17.swagger对接口文档进行管理")
                // 版本号
                .version("1.0")
               .termsOfServiceUrl("NO terms of service")
                // 描述
                .description("本教程配套代码github地址:https://github.com/Dominick-Li/springboot-master")
                //作者
                .license("The Apache License, Version 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .build();
    }
} 

注解描述

API接口注解
常用注解
@Api : 用在类上,描述该类的主要作用。
@ApiOperation:用在方法上,描述该方法主要作用。
@ApiImplicitParams : 用在方法上,包含一组参数说明。
@ApiImplicitParam: 用在方法上,用于描述一个参数说明

@RestController
@Api(tags = "用户管理相关接口")
@RequestMapping("/user")
public class UserController {

  @GetMapping("/")
  @ApiOperation("分页查询所有用户")
  public List<User> getUserById(@RequestBody PageParam pageParam) {
      return new ArrayList<User>();
  }

  @GetMapping("/{id}")
  @ApiOperation("根据id查询用户的接口")
  @ApiImplicitParam(name = "id", value = "用户id", required = true)
  public User getUserById(@PathVariable Integer id) {
     return new User();
  }


  @PostMapping("/")
  @ApiOperation("添加用户的接口")
  @ApiImplicitParams({
          @ApiImplicitParam(name = "username", value = "用户名", defaultValue = "李四"),
          @ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "北京", required = true)
  })
  public HttpResult addUser(String username, @RequestParam(required = true) String address) {
      return HttpResult.successResult();
  }

  @PutMapping("/{id}")
  @ApiOperation("根据id更新用户的接口")
  public HttpResult updateUserById(@RequestBody User user) {
      return HttpResult.successResult();
  }

}

模型类注解

常用注解

  • @ApiModel 描述该类的信息
  • @ApiModelProperty 描述该属性的信息
@ApiModel("用户类")
public class User {
    @ApiModelProperty("用户唯一id")
    private Integer id;

    @ApiModelProperty("用户名")
    private String username;

    @ApiModelProperty("密码")
    private String password;

    @ApiModelProperty("地址")
    private String address;
    //省略get set方法
} 
@ApiModel("Http结果响应")
public class HttpResult  implements Serializable {

    private static String successMessage = "操作成功";

    private static String errorMessage = "操作失败";

    @ApiModelProperty("响应码")
    private int code;

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

    @ApiModelProperty("响应消息")
    private String msg;

    public HttpResult(){ }

    public HttpResult(int code, String msg) {
        this.code=code;
        this.msg=msg;
    }

    public HttpResult(int code, String msg, Object data) {
        this.code=code;
        this.msg=msg;
        this.data=data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public Object getData() {
        return data;
    }

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

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public static HttpResult successResult() {
        return new HttpResult(HttpStatus.OK.value(), successMessage);
    }

    public static HttpResult successResult(String msg) {
        return new HttpResult(HttpStatus.OK.value(), defaultSuccessMsg(msg));
    }

    public static HttpResult successResult(Object obj) {
        return new HttpResult(HttpStatus.OK.value(), successMessage, obj);
    }

    public static HttpResult successResult(String msg, Object obj) {
        return new HttpResult(HttpStatus.OK.value(), defaultSuccessMsg(msg), obj);
    }

    public static HttpResult failureResult() {
        return new HttpResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), errorMessage);
    }

    public static HttpResult failureResult(String msg) {
        return new HttpResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), defautlErrorMsg(msg));
    }

    public static HttpResult failureResult(Integer code, String msg) {
        return new HttpResult(code, defautlErrorMsg(msg));
    }

    public static HttpResult failureResult(String msg, Object obj) {
        return new HttpResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), defaultSuccessMsg(msg), obj);
    }

    private static String defautlErrorMsg(String msg) {
        return StringUtils.isEmpty(msg)?errorMessage:msg;

    }

    private static String defaultSuccessMsg(String msg) {
        return StringUtils.isEmpty(msg)?successMessage:msg;
    }
}   

查看API接口文档

访问接口文档页面

访问http://localhost:8017/swagger-ui.html查看API接口文档

解决ApiModel类作为属性返回没有显示类描述

改造上面的HttpResult数据返回封装类

添加<T>让类变成泛型类

@ApiModel("Http结果响应")
public class HttpResult<T> implements Serializable {} 

设置data为泛型属性

 @ApiModelProperty("响应数据")
    private T data;
    public T getData() {
        return data;
    }

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

接口返回的时候指定返回类型

 @GetMapping("/{id}")
 public HttpResult<User> getUserById(@PathVariable Integer id) {
       return HttpResult.successResult(new User());
 }

  



 

posted @ 2021-04-06 14:19  hzy_叶子  阅读(123)  评论(0编辑  收藏  举报