• Swagger的简单介绍,集成,以及如何在生产环境中关闭swagger,在测试和开发环境中自动打开


    引言

    参考文章

    本篇文章前面部分讲解了何为Swagger,在项目中该如何去使用,以及注解及其相关说明,如果是想要了解如何去动态的关闭Swagger的,通过目录链接直接跳转即可

    1、什么是swagger?

    Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

    2、swagger的作用是什么?

    1)接口的文档在线自动生成。

    2)功能测试。

    3、swagger如何使用?

    这里建议swagger2的版本为2.9.2,springboot的版本为2.5.5以下,否则可能会出现空指针异常的问题

    第一步:导入swagger依赖包

    <dependency>
    
       <groupId>io.springfoxgroupId>
    
       <artifactId>springfox-swagger2artifactId>
    
       <version>2.9.2version>
    
    dependency>
    
    <dependency>
    
       <groupId>io.springfoxgroupId>
    
       <artifactId>springfox-swagger-uiartifactId>
    
       <version>2.9.2version>
    
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    第二步:创建swagger配置文件

    如果只是需要在项目中简单使用以下使用方式1即可

    方式一

    /**
     * Swagger2的接口配置
     */
    @Configuration
    @EnableSwagger2
    @Profile({"dev", "test"})
    public class SwaggerConfig {
        /**
         * 系统基础配置
         */
        @Autowired
        private RpcsConfig rpcsConfig;
    
        /**
         * 创建API
         */
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .pathMapping("/dev-api")
                    // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
                    .apiInfo(apiInfo())
                    // 设置哪些接口暴露给Swagger展示
                    .select()
                    // 扫描所有有注解的api,用这种方式更灵活
                    .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                    // 扫描指定包中的swagger注解
                    //.apis(RequestHandlerSelectors.basePackage("com.ryi.rpcs.project.tool.swagger"))
                    // 扫描所有 .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build()
                    /* 设置安全模式,swagger可以设置访问token */
                    .securitySchemes(securitySchemes())
                    .securityContexts(securityContexts());
        }
    
        /**
         * 添加摘要信息
         */
        private ApiInfo apiInfo() {
            // 用ApiInfoBuilder进行定制
            return new ApiInfoBuilder()
                    // 设置标题
                    .title("标题:快速预安检系统_接口文档")
                    // 描述
                    .description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...")
                    // 作者信息
                    .contact(new Contact(rpcsConfig.getName(), null, null))
                    // 版本
                    .version("版本号:" + rpcsConfig.getVersion())
                    .build();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    方式二

    package com.ryi.rpcs.framework.config;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.context.annotation.Profile;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.ApiKey;
    import springfox.documentation.service.AuthorizationScope;
    import springfox.documentation.service.Contact;
    import springfox.documentation.service.SecurityReference;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spi.service.contexts.SecurityContext;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    /**
     * Swagger2的接口配置
     */
    @Configuration
    @EnableSwagger2
    @Profile({"dev", "test"})
    public class SwaggerConfig {
        /**
         * 系统基础配置
         */
        @Autowired
        private RpcsConfig rpcsConfig;
    
        /**
         * 创建API
         */
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .pathMapping("/dev-api")
                    // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
                    .apiInfo(apiInfo())
                    // 设置哪些接口暴露给Swagger展示
                    .select()
                    // 扫描所有有注解的api,用这种方式更灵活
                    .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                    // 扫描指定包中的swagger注解
                    //.apis(RequestHandlerSelectors.basePackage("com.ryi.rpcs.project.tool.swagger"))
                    // 扫描所有 .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build()
                    /* 设置安全模式,swagger可以设置访问token */
                    .securitySchemes(securitySchemes())
                    .securityContexts(securityContexts());
        }
    
        /**
         * 安全模式,这里指定token通过Authorization头请求头传递
         */
        private List<ApiKey> securitySchemes() {
            List<ApiKey> apiKeyList = new ArrayList<ApiKey>();
            apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
            return apiKeyList;
        }
    
        /**
         * 安全上下文
         */
        private List<SecurityContext> securityContexts() {
            List<SecurityContext> securityContexts = new ArrayList<>();
            securityContexts.add(
                    SecurityContext.builder()
                            .securityReferences(defaultAuth())
                            .forPaths(PathSelectors.regex("^(?!auth).*$"))
                            .build());
            return securityContexts;
        }
    
        /**
         * 默认的安全上引用
         */
        private List<SecurityReference> defaultAuth() {
            AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
            AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
            authorizationScopes[0] = authorizationScope;
            List<SecurityReference> securityReferences = new ArrayList<>();
            securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
            return securityReferences;
        }
    
        /**
         * 添加摘要信息
         */
        private ApiInfo apiInfo() {
            // 用ApiInfoBuilder进行定制
            return new ApiInfoBuilder()
                    // 设置标题
                    .title("标题:快速预安检系统_接口文档")
                    // 描述
                    .description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...")
                    // 作者信息
                    .contact(new Contact(rpcsConfig.getName(), null, null))
                    // 版本
                    .version("版本号:" + rpcsConfig.getVersion())
                    .build();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110

    4、注解及其说明

    • @Api : 用在类上,描述该类的主要作用。

    • @ApiOperation:用在方法上,给API增加方法描述。

    • @ApiImplicitParams : 用在方法上,包含一组参数描述。

    • @ApiImplicitParam:用来注解来给方法入参增加描述。

    • @ApiResponses:用于表示一组响应。

    • @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息。

    ​ - code:数字,例如500

    ​ - message:信息,例如"请求参数异常"

    ​ - response:抛出异常的类

    • @ApiModel:用在返回对象类上,描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)。

    • @ApiModelProperty:描述一个model的属性。

    关闭Swagger的三种方式

    方式一:

    在Swagger2Config上使用@Profile注解标识,@Profile({“dev”,“test”})表示在dev和test环境才能访问swagger-ui.html,prod环境下访问不了。

    方式二:

    在Swagger2Config上使用@ConditionalOnProperty注解,

    @ConditionalOnProperty(name = “swagger.enable”, havingValue = “true”)

    表示配置文件中如果swagger.enable =true表示开启。所以只需要在开发环境的配置文件配置为true,生产环境配置为false即可。

    方式三:

    application.yml中写一个swagger.enable=trueswagger.enable=false的值,之后在SwaggerConfig类中通过@Value("${swagger.enable}")读取其值,对swagger配置中的enable进行动态属性赋值开关即可

    = “true”)**

    表示配置文件中如果swagger.enable =true表示开启。所以只需要在开发环境的配置文件配置为true,生产环境配置为false即可。

    方式三:

    application.yml中写一个swagger.enable=trueswagger.enable=false的值,之后在SwaggerConfig类中通过@Value("${swagger.enable}")读取其值,对swagger配置中的enable进行动态属性赋值开关即可

    个人比较喜欢第一种方式,因为第二种方式还要在每个环境文件中去配置,并维护;Swagger一般用于开发和测试环境,所以直接限制Swagger启用的环境为dev和test即可,这样也不需要再维护配置文件了。

  • 相关阅读:
    数据结构-----哈夫曼树和哈夫曼编码
    Vue学习笔记(十一):路由管理
    记录nvm use node.js版本失败,出现报错: exit status 1: ��û���㹻��Ȩ��ִ�д˲�����
    组合计数3以及高斯消元
    精选版:用Java扩展Nginx(nginx-clojure 入门)
    我的创作纪念日
    mysql的锁介绍
    进程的调度
    Matplotlib补充:科研绘图利器(写论文、数据可视化必备)
    awk进阶
  • 原文地址:https://blog.csdn.net/qq_49137582/article/details/126100897