zoukankan      html  css  js  c++  java
  • 简单了解一下 Swagger

    一、Swagger

    1、什么是 Swagger ?

      Swagger 是一个规范和完整的框架,用于生成、描述、调用以及可视化的 Restful 风格的 Web 服务。
      简单的理解:是一款 REST API 文档生成工具,生成在线的接口文档,方便接口测试。

    2、为什么使用 Swagger?

      前后端分离开发时,为了方便前后端接口调用规范,需要提供一个接口文档,但是维护这个接口文档是一个及其繁琐的事情,可能一不小心就忘记更新该文档从而导致前后端接口调用失败。
      Swagger 就是为了解决这个问题而出现的(在线接口文档),其在接口方法上定义注解,并根据注解形成一个 html 页面,每次接口修改,这个 html 页面就会发生相应的改变,从而保证了接口文档的正确性。通过该 html 页面,可以很方便、清楚的知道这个接口的功能,并测试。

    3、SpringBoot 整合 Swagger?

    (1)Step1:
      导入依赖 jar 包。

    <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>

    (2)Step2:
      配置 swagger 插件。
      编写一个配置类,实现 WebMvcConfigurer 接口(可以不实现该接口),用于配置 Swagger 相关信息。
      @EnableSwagger2 用于开启 Swagger。

    package com.lyh.test.test_mybatis_plus.config;
    
    import io.swagger.annotations.ApiOperation;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig implements WebMvcConfigurer {
    
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 加了ApiOperation注解的类,才会生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 指定包下的类,才生成接口文档
                .apis(RequestHandlerSelectors.basePackage("com.lyh.test.test_mybatis_plus.controller"))
                .paths(PathSelectors.any())
                .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                .title("Swagger 测试")
                .description("Swagger 测试文档")
                .termsOfServiceUrl("https://www.cnblogs.com/l-y-h/")
                .version("1.0.0")
                .build();
        }
    }

    (3)启动服务,并访问 swagger-ui.html 页面。
      访问 http://localhost:8080/swagger-ui.html,显示如下,能够进入在线接口文档页面,由于并没有在方法上添加注解,所以接口方法都没有显示。

    (4)给接口方法添加相关注解。
      由于配置了 @ApiOperation 注解标注的方法才能被扫描到,所以在方法上添加该注解。

    @RestController
    @RequestMapping("/test_mybatis_plus/user")
    public class UserController {
        @Autowired
        private UserService userService;
    
        @ApiOperation("获取所有用户")
        @GetMapping("/test")
        public Result list() {
            return Result.ok().data("items", userService.list());
        }
    }

    (5)重启服务,再次访问 swagger-ui.html 页面。

     

     

    二、Swagger 注解、配置

    1、Swagger 常用注解

    (1)常用注解
      swagger 通过注解去实现接口文档,这些注解可以标注接口名,请求方法,参数,返回信息等。

    @Api                标注在 controller 类上,用于修饰 controller
    @ApiOperation       标注在接口方法上,用于修饰 接口方法
    @ApiParam           标注在接口参数上,用于修饰 参数
    @ApiImplicitParam   标注在接口参数上,用于修饰 一个请求参数
    @ApiImplicitParams   标注在接口参数上,用于修饰 多个请求参数(@ApiImplicitParam)
    @ApiIgnore          标注在方法、参数上,表示忽略该方法、参数
    @ApiModel           标注在实体类上,用来修饰实体类
    @ApiModelProperty   标注在实体类的属性上,用于修饰实体类的属性。

    (2)@Api  @ApiOperation @ApiImplicitParam @ApiImplicitParams 举例:

    import com.lyh.test.test_mybatis_plus.entity.User;
    import com.lyh.test.test_mybatis_plus.service.UserService;
    import com.lyh.test.test_mybatis_plus.util.Result;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiImplicitParam;
    import io.swagger.annotations.ApiImplicitParams;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    /**
     * <p>
     *  前端控制器
     * </p>
     *
     * @author lyh
     * @since 2020-05-08
     */
    @RestController
    @RequestMapping("/test_mybatis_plus/user")
    @Api(value = "UserController", tags = "用户接口文档")
    public class UserController {
        @Autowired
        private UserService userService;
    
        @ApiOperation("获取所有用户")
        @GetMapping("/list")
        public Result list() {
            return Result.ok().data("items", userService.list());
        }
    
        // paramType ="query" 对应 @RequestParam
        // paramType ="path" 对应 @PathVariable
        // paramType ="body" 对应 @RequestBody 不经常用
        // paramType ="header" 对应 @RequestHeader
        @ApiImplicitParams({
                @ApiImplicitParam(name = "id", required = false, value = "用户 ID", paramType ="query", dataType = "Long"),
                @ApiImplicitParam(name = "user", required = false, value = "用户信息", paramType ="body", dataType = "User")
        })
        @ApiOperation("新增用户")
        @PutMapping("/update")
        public Result update(@RequestBody User user, @RequestParam(required = false) Long id) {
            System.out.println("==================");
            System.out.println(id);
            if (userService.save(user)) {
                return Result.ok().message("数据更新成功");
            } else {
                return Result.error().message("数据更新失败");
            }
        }
    }

     

    (3)@ApiModel  、@ApiModelProperty 举例

    @Data
    @ApiModel("统一结果返回类结构")
    public class Result {
        /**
         * 响应是否成功,true 为成功,false 为失败
         */
        @ApiModelProperty("响应是否成功,true 为成功,false 为失败")
        private Boolean success;
    
        /**
         * 响应状态码, 200 成功,500 系统异常
         */
        @ApiModelProperty("响应状态码, 200 成功,500 系统异常")
        private Integer code;
    
        /**
         * 响应消息
         */
        @ApiModelProperty("响应消息")
        private String message;
    
        /**
         * 响应数据
         */
        @ApiModelProperty("响应数据")
        private Map<String, Object> data = new HashMap<>();
    }

     

    2、Swagger 配置

    (1)简介
      上面简单了解了下 swagger 常用注解,此处简单介绍一下 swagger 的配置类。

    (2)配置类举例
      根据项目情况修改 apiInfo、apis、paths 等信息。
    其中:
      apiInfo 用于定义 接口文档的基本信息。
      apis 用于定义 接口扫描规则。
      paths 用于定义 路径过滤规则。

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig implements WebMvcConfigurer {
    
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 加了ApiOperation注解的类,才会生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 指定包下的类,才生成接口文档
                .apis(RequestHandlerSelectors.basePackage("com.lyh.test.test_mybatis_plus.controller"))
                .paths(PathSelectors.any())
                .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                .title("Swagger 测试")
                .description("Swagger 测试文档")
                .termsOfServiceUrl("https://www.cnblogs.com/l-y-h/")
                .version("1.0.0")
                .build();
        }
    }

    (3)分析
    Step1:简单了解一下注解。
      @EnableSwagger2 注解用于开启 swagger。
      @Bean 注解标注 createRestApi 方法用于实例 Docket 对象(文档插件)并交给 Spring 容器进行管理。

    Step2:简单了解一下 apiInfo。
      该方法用于定义 API 文档的基本信息。

    【属性简单介绍:】
        title                  标题,默认为 Api Documentation
        version                版本,默认为 1.0
        description            描述信息,默认为 Api Documentation
        termsOfServiceUrl      服务地址,默认为 urn:tos
        license                许可证,默认为 Apache 2.0
        licenseUrl             许可证地址,默认为 http://www.apache.org/licenses/LICENSE-2.0
        contact                定义作者信息
    
    【举例:】
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("后台管理系统 API 文档")
            .description("本文档描述了后台管理系统相关接口的定义")
            .termsOfServiceUrl("https://www.cnblogs.com/l-y-h/")
            .version("1.0.0")
            .contact(new Contact("lyh", "https://www.cnblogs.com/l-y-h/", "13865561381@163.com"))
            .build();
    }

    Step3:简单了解一下 Docket
      Docket 实现了 DocumentationPlugin 接口,即文档插件。
      Docket 常用方法介绍。

    【Docket 常用方法:】
        apiInfo()              用于定义接口文档的基本信息。
        enabled()              用于定义 swagger 是否使用。
        select()               实例化一个 ApiSelectorBuilder,调用其 build 方法返回一个 Docket 对象。 
        
    【ApiSelectorBuilder 常用方法:】
        apis()                 用于定义接口扫描方式(可以使用 RequestHandlerSelectors 指定扫描规则)
        paths()                用于过滤路径(可以使用 PathSelectors 去指定过滤规则)。
        build()                返回一个 Docket 对象
    注:
        RequestHandlerSelectors 常用方法:
           any()                     扫描全部
           none()                    全部不扫描
           withMethodAnnotation()    根据方法上的注解扫描
           withClassAnnotation()     根据类上的注解扫描
           basePackage()              指定要扫描的包
      
       PathSelectors 常用方法:
           any()                      全部通过
           none()                     全部不通过
           regex()                    根据正则表达式匹配是否通过
           
    【举例:】
    
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig implements WebMvcConfigurer {
        @Value("${spring.profiles.active:#{null}}")
        private String env;
    
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // 指定是否开启 swagger(如下,生产环境时不执行 swagger)
                .enable("prod".equals(env) ? false : true)
                // 指定分组名
                .groupName("user")
                .select()
                // 加了ApiOperation注解的类,才会生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 指定包下的类,才生成接口文档
                .apis(RequestHandlerSelectors.basePackage("com.lyh.test.test_mybatis_plus.controller"))
                // 不过滤接口
                .paths(PathSelectors.any())
                .build();
        }
    }

  • 相关阅读:
    [AGC030F] Permutation and Minimum
    nginx
    Flex建立AS项目时,如何设定发布的舞台大小
    让Flex 支持VSS
    Flex编程实用技巧
    Flash/Flex学习笔记(57):实用技巧
    sql 2000 "无法执行查询,因为一些文件缺少或未注册"的解决办法
    Flash/Flex学习笔记(56):矩阵变换
    什么是反向代理,如何利用反向代理提高网站性能
    AS3及Flex的百条常用知识
  • 原文地址:https://www.cnblogs.com/l-y-h/p/12872748.html
Copyright © 2011-2022 走看看