知識庫 / Spring / Spring Boot RSS 訂閱

如何在生產環境中關閉 Swagger-ui

REST,Spring Boot
HongKong
9
03:48 AM · Dec 06 ,2025

1. 概述

Swagger 用户界面允許我們查看有關我們 REST 服務的信息。這對於開發非常方便。然而,由於安全考慮,我們可能不希望在公共環境中啓用此功能。

在本簡短教程中,我們將探討 如何 在生產環境中關閉 Swagger。

2. Swagger 配置

為了使用 SpringDoc 設置 Swagger,我們將它定義在一個配置 Bean 中。

讓我們創建一個 SwaggerConfig 類:

@Configuration
public class SwaggerConfig {
    
    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI().info(new Info().title("SpringDoc Disable SwaggerUI example")
            .description("SpringDoc Disable SwaggerUI application")
            .version("v0.0.1"));
    }
}

默認情況下,此配置 Bean 會始終注入到我們的 Spring 上下文中。因此,Swagger 對所有環境均可用。

要禁用生產環境中的 Swagger,請切換此配置 Bean 是否注入。

3. 使用 Spring 配置文件

在 Spring 中,我們可以使用 <em @Profile</em> 註解來啓用或禁用 Bean 的注入。

讓我們嘗試使用 SpEL 表達式來匹配 “swagger” 配置文件,但不匹配 “prod” 配置文件:

@Profile({"!prod && swagger"})

這迫使我們明確指定希望激活 Swagger 的環境。同時,這也有助於防止在生產環境中意外啓用 Swagger。

我們可以將註解添加到我們的配置中:

@Configuration 
@Profile({"!prod && swagger"})
public class SwaggerConfig {
    ...
}

現在,讓我們通過使用不同設置的 spring.profiles.active 屬性啓動我們的應用程序來測試其功能:

-Dspring.profiles.active=prod // Swagger is disabled

-Dspring.profiles.active=prod,anyOther // Swagger is disabled

-Dspring.profiles.active=swagger // Swagger is enabled

-Dspring.profiles.active=swagger,anyOtherNotProd // Swagger is enabled

none // Swagger is disabled

4. 使用條件語句

Spring 配置文件可能對於功能開關來説過於粗粒度。這種方法可能導致配置錯誤以及龐大且難以管理的配置文件列表。

作為替代方案,我們可以使用 <em @ConditionalOnExpression</em>>,它允許指定自定義屬性以啓用 Bean:

@Configuration
@ConditionalOnExpression(value = "${useSwagger:false}")
public class SwaggerConfig {
    ...
}

如果“useSwagger”屬性缺失,則默認值為 false

要進行測試,我們可以通過在 application.properties (或 application.yaml) 文件中設置該屬性,或將其作為 VM 選項來設置。

-DuseSwagger=true

我們應該注意的是,這個示例並未提供任何確保生產實例不會意外地將 useSwagger 設置為 true 的方法。

5. 避免潛在問題

如果啓用 Swagger 存在安全問題,則我們需要選擇一種既安全又易於使用的策略。

某些 SpEL 表達式在結合使用 @Profile 時,可能會與此目標相悖。

@Profile({"!prod"}) // Leaves Swagger enabled by default with no way to disable it in other profiles
@Profile({"swagger"}) // Allows activating Swagger in prod as well
@Profile({"!prod", "swagger"}) // Equivalent to {"!prod || swagger"} so it's worse than {"!prod"} as it provides a way to activate Swagger in prod too

這正是我們使用 @Profile 示例的原因。

@Profile({"!prod && swagger"})

該解決方案可能是最嚴格的,因為它默認情況下禁用了 Swagger,並且保證它不能在“prod”環境中啓用。

6. 結論

在本文中,我們探討了在生產環境中禁用 Swagger 的解決方案。

我們研究了通過使用 @Profile@ConditionalOnExpression 註解來切換啓用 Swagger 的 Bean。我們還考慮瞭如何防止配置錯誤和不希望出現的默認設置。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.