springfox
在 Spring Boot 2.6 開始就有很多兼容性 bug(主要是 Spring MVC PathPatternParser 的引入),導致在 Spring Boot 2.6/2.7 里經常出現 無法啟動 / 無法訪問 swagger-ui.html 的情況。
🔎 問題原因
Spring Boot 2.6 開始默認使用
PathPatternParser
代替了AntPathMatcher
,而springfox 3.0.0
沒有適配新的PathPatternParser
。所以導致 Springfox 在 Spring Boot 2.6/2.7 下訪問 swagger 出現 404 或 bean 初始化錯誤。
? 解決方案
方案 1:修改配置兼容 Springfox
在 application.yml
或 application.properties
中強制使用 AntPathMatcher
:
spring:mvc:pathmatch:matching-strategy: ant_path_matcher
這樣就能避免 Springfox 跟 PathPatternParser
沖突。
適合仍想繼續用 springfox-swagger2
/ springfox-boot-starter
的情況。
方案 2:升級到 springdoc-openapi
官方推薦的做法是放棄 springfox
,遷移到 springdoc-openapi
,它是 Swagger 3.0/OpenAPI 3.1 的社區主流實現,兼容 Spring Boot 2.7 / 3.x。
依賴:
<dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-ui</artifactId><version>1.7.0</version>
</dependency>
訪問地址:
Swagger UI:
http://localhost:8080/swagger-ui.html
OpenAPI JSON:
http://localhost:8080/v3/api-docs
遷移成本也不高,大多數注解 (@Api
, @ApiOperation
) 可以直接用 @Operation
, @Schema
等替代。
方案 3:降級 Spring Boot
如果必須使用 Springfox 3.0 且不想切換 springdoc
,可以把 Spring Boot 版本降到 2.5.x,這是最后一個與 Springfox 兼容良好的版本。
不過這種方案不推薦,會錯過 Spring Boot 2.6+ 的 bug 修復和優化。
🔧 建議
短期:如果只是想快速解決,直接在
application.yml
加上matching-strategy: ant_path_matcher
。長期:建議遷移到
springdoc-openapi
,它更新活躍、支持 Spring Boot 3.x、JDK 17+。