• 在生产环境中禁用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

  • 相关阅读:
    idea开发工具关于svn上代码的颜色
    写一个Request包装类ExternalApiHttpServletRequestWrapper(外部接口请求使用用于解密)
    什么情况下,需要用事务?
    SpringBoot 2.1.6.RELEASE ->SpringCloudAlibaba
    oracle查看锁表进程,杀掉锁表进程
    JavaScript 闭包
    萤石云定时更新 accessToken
    Ubuntu Linux的DevExpressReport无法显示报表(.net core)
    Vue在IE下打开空白解决方案
    DFT scan chain 介绍
  • 原文地址:https://www.cnblogs.com/weijs/p/14153363.html
Copyright © 2020-2023  润新知