zoukankan      html  css  js  c++  java
  • 在生产环境中禁用Swagger

    一、采用的方案
    1. 在class中
    @Configuration
    //配置是否开启swagger的访问的方式一,动态读取无法使用,@active@
    //@Profile({"dev", "test", "local", "uat-local"})            
    //配置是否开启swagger的访问的方式二,要在yml中添加对应配置
    @ConditionalOnProperty(name = "swagger.enable", havingValue = "true")      
    @EnableSwagger2 //Enable swagger 2.0 spec
    public class SwaggerConfig {
        
    2. 在yml文件中
    # 是否启用swagger,true则启用
    swagger:
      enable: true  
     
    二、实现方案:
     
    1. @Profile({"dev", "test", "local", "uat-local"})。实际使用中,配置文件为动态设置,无法使用方案一
    spring: profiles: active: @active@
    2. @ConditionalOnProperty(name = "swagger.enable", havingValue = "true") 。不需要开放访问则不配置或者配置为非true
    # 是否启用swagger,true则启用 swagger: enable: true
    3. 在Docket中设置,体验上会比方案2友好
    @Value("${swagger.enable}")
    private Boolean swaggerEnable;
    
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(swaggerEnable)
    
    # 是否启用swagger,true则启用
    swagger:
      enable: true
    4. 拦截器
    @Component public class SwaggerInterceptor implements HandlerInterceptor {
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (StringUtils.trim(activeProfile).equals("uat") || StringUtils.trim(activeProfile).equals("prod")) {
          return false;
        } return true;
       }
    ...
     
    @Configuration public class InterceptorConfig implements WebMvcConfigurer {
      //spring-boot 2.x 的写法
      @Override public void addInterceptors(InterceptorRegistry registry) {
        logger.info("拦截器注册", "SwaggerInterceptor", null);
        registry.addInterceptor(swaggerInterceptor).addPathPatterns(SWAGGER_UI_URL);
      }
    ...
    5. 在nginx或者服务网关中处理
     
    三、遇到的问题:
     
    1. 测试过程中,方法一与方法二都无效,排查后确认原因:
      启动类中也有一个启动swagger的配置,所以在SwaggerConfig中失效的情况下,依然有效
    @EnableSwagger2 public class Application
      解决方法:注释掉//@EnableSwagger2

  • 相关阅读:
    c# 自定义位数生成激活码
    接口interface和抽象类型abstract
    winform自动升级方案
    泛型介绍
    泛型约束形式
    登录状态保持Session/Cookie
    EFCore 2.0引用标量函数
    .net生成条形码
    通用手机号、身份证号等隐藏显示方法
    .net core api Post请求
  • 原文地址:https://www.cnblogs.com/weijs/p/14153363.html
Copyright © 2011-2022 走看看