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+。