是否可以僅在 Swagger UI 中公開某些選定的端點,但通過直接 HTTP 呼叫使它們在服務器上不可用?
不能在 Swagger UI中@Operation(hidden=true)公開端點,但仍然可以在服務器上使用它。我只需要“倒置的行為”。
用例:我們在生產中通常禁止使用 Swagger UI。我想讓一些端點僅在 Swagger UI 中可用,用于開發期間的測驗目的。
版本:Spring Boot 2.6.2、springdoc-openapi-ui 1.6.3。
uj5u.com熱心網友回復:
用例:
- 我們在生產中通常禁止使用 Swagger UI。
- 我想讓一些端點僅在 Swagger UI 中可用,用于開發期間的測驗目的。
這種(需求型別)的“最有彈性”的解決方案可能是Profiles!
我們可以:
@SpringBootApplication(exclude = {
SpringDocWebMvcConfiguration.class,
SpringDocConfiguration.class
})
public class MySpringApp {...
從我們的主配置(默認組態檔)中排除 openapi 配置(因為無論如何都是禁止的)。
然后我們會介紹:
@Configuration
@Profile("documented") // ! this gets only activated/loaded, when "documented" is (one of) spring.aprofiles.active
@Import({
SpringDocWebMvcConfiguration.class,
SpringDocConfiguration.class
})
// customize API here ...
class DocConfig {
// ...and/or here
}
我們想要“招搖”的所有控制器,我們還注釋:
@Profile("documented")
@[Rest]Controller public class MyDevController {
...
不幸的是,我們只能@Profile在 bean 方法/類上使用,要按“請求映射”(方法)使用它,我們必須復制和隔離控制器:
一個:
@Profile("documented") // work in progress
和原始控制器:
@Profile("!documented") // as in prod
我們必須將它們相互排除("documented"vs "!documented"),否則(路徑)映射將不會不同。
有了這個,在生產中運行我們的應用程式(沒有“記錄的”組態檔),將:
- 跳過springdoc配置
- 公開號:
- 招搖-ui
- 沒有 api 端點
- 不加載任何帶有“已記錄”組態檔的控制器。
在 dev/loaclly 中運行我們的應用程式,我們會設定spring.profiles.active=documented,springdoc 會:
- 暴露 ui 和端點:
- “記錄”(和默認!)控制器。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/410160.html
標籤:
