SpringBoot入门实践(八)-使用Swagger2构建强大的API文档

 个人博客:兰陵笑笑生,欢迎浏览博客!html

 上一章 SpringBoot入门实践(七)-Spring-Data-JPA实现数据访问当中,咱们介绍了如何在项目中使用 Spring Data JPA来进行数据库的访问。本章将继续探索springBoot的其余功能,如何快速高效的构建在线的API文档。java

一 、前言

 现在先后端分离,那么在先后端对接的时候少不了接口的文档,过去咱们都是手写一个wold文档,我相信做为一个写代码的,最不肯意的就是写各种的文档。固然接口文档是必须的。可是咱们手动维护的API文档在效率方面的确比较慢。并且还容易出错,最最要命的是随着项目的迭代,接口在不断的改变,实时的更新接口文档,是一件很分神的事情,今天咱们就简单的介绍一个如何使用Swagger2快速的生成在线文档。web

2、 简介

 在Swagger的官方网站上https://swagger.io/ 是这样据介绍的,Swagger是实现了OpenApi标准的文档使用工具,包含了各类开源的工具集。spring

  • Swagger Core 用于生成Swagger的API规范的事例
  • Swagger UI 生成一个界面,咱们这里就会用到。
  • SwaggerHub API设计和文档化
  • ...

三 、快速上手

3.1 引入依赖

 在构建好Restful API 后,咱们首先在pom.xml文件中引入Swagger2和Swagger UI的依赖:数据库

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

3.2 Swagger2的配置

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Conf {

    /**
     * 控制http://localhost:8081/swagger-ui.html#/的显示
     * @return
     */
    @Bean
    public Docket controllerApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("标题:某公司_接口文档")
                        .description("描述:用于XXXX功能,具体包括XXX,XXX模块...")
                        .contact(new Contact("Socks", null, null))
                        .version("版本号:1.0")
                        .build())
                .select()
                //选择的包名
                .apis(RequestHandlerSelectors.basePackage("com"))
                .paths(PathSelectors.any())
                .build();
    }
}

3.3 访问地址

file

到这里,swagger2的应用能够说快速的入门,可使用了,可是咱们可能须要对Controller、方法作一些说明,咱们能够经过如下额API精细化管理能够实现。json

3.4 API精细化管理

 首先的介绍几个经常使用的注解:segmentfault

3.4.1 @Api :添加在Controller控制器上,用来解释当前的控制器

  • value:貌似没什么用
  • tags:描述这个控制器的,
  • protocols:协议类型:http
  • hidden:没什么用后端

    @Api(value = "value", tags = "用戶管理", hidden = true)
    @RestController
    @RequestMapping("/api/v1/user")
    public class UserController {
    ....
    }

3.4.2 @ApiOperation:注解添加在方法上,用来解释当前的方法,包括用户返回值

  • value api的解释
  • notes api的注意事项
  • response 返回的类型等

3.4.3 @ApiIgnore: 做用在REST API控制器方法上,则该API不会被显示出来:api

@ApiOperation(value = "删除列表", notes = "注意", response = HttpResponse.class)
    @ApiIgnore
    @DeleteMapping("/delete/{id}")
    public HttpResponse delete(@PathVariable Long id) {
        userMap.remove(id);
        return HttpResponse.ok();
    }

3.4.4 @ApiImplicitParams和@ApiImplicitParam ,用来解释方法的参数,

@ApiImplicitParams是能够包含多个@ApiImplicitParam,如app

/**
     * 列表请求
     * @return
     */
    @ApiOperation(value = "用户列表",notes = "注意",response = HttpResponse.class)
    @RequestMapping(path = "/list",method = RequestMethod.PUT, 
    consumes = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name="userName",value = "用戶名称"),
            @ApiImplicitParam(name="age",value = "用戶年龄")
    })
    public HttpResponse list(String userName ,Integer age) {
        List<User> user = new ArrayList<>(userMap.values());
        return HttpResponse.ok().setData(user);
    }

这样API文档就丰富了不少:

file

file

3.4.5 POJO 对象解释

 在生成的在线API文档中,不少时候咱们须要对POJO中的字段作一些解释,好比下图的User添加一个描述,对每一个字段添加一个描述,以及他的类型作一个解释,这里固然也可以使用Swagger2的其余2个注解:@ApiModel和 @ApiModelProperty,没有使用注解的时候以下图:

file

3.4.5.1 : @ApiModel 添加在POJO 类上

  • value:默认是类名
  • description:对当前的POJO的描述

3.4.5.1:@ApiModelProperty

  • name:属性,默认pojo属性
  • value:值
  • nodtes:注意事项
  • dataType:属性类型
  • required:是否必须
  • allowEmptyValue :是否容许空置
  • allowableValues :容许的值
package com.miroservice.chapter2.pojo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(value = "user",description = "用户")
public class User {
    
    @ApiModelProperty(value = "用户ID",notes = "notes",dataType = "long",required = false,allowEmptyValue = true)
    private Long id;
    
    @ApiModelProperty(value ="用户名称",notes = "notes",dataType = "String",required = false,allowEmptyValue = true)
    private String userName;

    @ApiModelProperty("用户年齡")
    private Long age;
    ...
}

这样保存的用户的每一个属性都有了解释:

file

3.5 生产环境关闭Swagger2

 咱们使用Swagger2是为了方便开发,可是如在把这样的文档在生产环境开启,那我估计过不了多久工做就没了,如何才能在正式环境禁止使用Swagger2呢,其实很简单。咱们能够在配置swagger的使用,添加一个注解:

@ConditionalOnProperty,并经过配置文件配置swagger.enable=true的时候,才开启swagger,以下配置:

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

    /**
     * 控制http://localhost:8081/swagger-ui.html#/的显示
     * @return
     */
    @Bean
    public Docket controllerApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("标题:某公司_接口文档")
                        .description("描述:用于XXXX功能,具体包括XXX,XXX模块...")
                        .contact(new Contact("Socks", null, null))
                        .version("版本号:1.0")
                        .build())
                .select()
                //选择的包名
                .apis(RequestHandlerSelectors.basePackage("com"))
                .paths(PathSelectors.any())
                .build();
    }
}

四 、总结

 这一篇文章简单的介绍了springBoot如何集成Swagger2快速的构建在线的API文档,包括各类注解的详细的解释,固然Swagger2的强大之处不只于此,还提供了更多扩展的功能,包括API分组,为每一个API配置Token,生成静态的文档等,有兴趣的能够本身深刻研究,本章的介绍对于平时的开发应该是够用了。

 以上就是本期的分享,你还能够关注本博客的#Spring Boot入门实践系列!#

本文由博客一文多发平台 OpenWrite 发布!
个人博客[兰陵笑笑生] ( http://www.hao127.com.cn/),欢...
相关文章
相关标签/搜索