在生產環境中禁用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM