一、采用的方案
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