Spring Boot集成Swagger 3.0时出现405 Method Not Allowed及白标错误页面问题
先梳理下你的核心问题:
- 添加
@Configuration后Spring Boot启动失败 - Swagger UI访问出现白标错误页面
- Postman发送GET请求返回
405 Method Not Allowed
这些问题大多源于Spring Boot 2.7.x和Springfox 3.0.0的兼容性冲突,以及Swagger 3.0的配置误用,下面逐个解决:
1. 修复Swagger配置,解决启动失败问题
你当前用了@EnableSwagger2,但这是Swagger 2.x的注解,Swagger 3.0(对应OpenAPI 3)应该用@EnableOpenApi。同时Spring Boot 2.6+默认的路径匹配策略和Springfox不兼容,导致加@Configuration后启动失败,需要调整配置:
正确的Swagger配置类
package hr.ogcs.blueprint; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.oas.annotations.EnableOpenApi; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration @EnableOpenApi // 替换原来的@EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.OAS_30) .select() .apis(RequestHandlerSelectors.basePackage("hr.ogcs.blueprint")) .paths(PathSelectors.any()) .build(); } }
添加路径匹配策略配置
在application.properties或application.yml中添加:
# 兼容Springfox的路径匹配策略 spring.mvc.pathmatch.matching-strategy=ant_path_matcher
这个配置是因为Spring Boot 2.6+默认使用path_pattern_parser,而Springfox 3.0.0还依赖旧的ant_path_matcher,不配置的话会导致启动时出现Bean冲突或路径解析错误。
2. 修复Gradle依赖,解决Swagger UI白标错误
你之前用springfox-boot-starter启动失败,其实是因为没加上面的路径匹配配置。现在可以换回官方的starter,或者保持现有依赖,但要确保版本一致:
推荐的Gradle依赖配置
dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-mongodb' implementation 'org.springframework.boot:spring-boot-starter-web' // 用springfox-boot-starter替代单独的swagger2和swagger-ui implementation 'io.springfox:springfox-boot-starter:3.0.0' testImplementation 'org.springframework.boot:spring-boot-starter-test' }
访问正确的Swagger UI路径
Swagger 3.0的UI路径是 http://localhost:8080/swagger-ui/(注意末尾的斜杠),而不是旧版的/swagger-ui.html。如果访问路径错误,就会出现白标错误页面。
3. 解决Postman GET请求405 Method Not Allowed错误
这个错误通常有两种原因:
- Controller中没有对应的GET映射:检查你的Controller类,确保有
@GetMapping注解的方法,且路径和你Postman请求的路径完全一致(注意大小写、参数等)。 - 请求路径被拦截:如果你的请求路径和Swagger的内置路径冲突(比如不小心用了
/swagger开头的路径),调整Controller的映射路径即可。 - 跨域问题(较少见):如果是跨域请求,需要在Controller上添加
@CrossOrigin注解,或者配置全局跨域规则。
额外建议:改用springdoc-openapi(更兼容新Spring Boot版本)
Springfox已经停止维护了,对于Spring Boot 2.7+,更推荐使用springdoc-openapi,它完全兼容OpenAPI 3,配置更简单:
Gradle依赖
dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-mongodb' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springdoc:springdoc-openapi-ui:1.6.14' testImplementation 'org.springframework.boot:spring-boot-starter-test' }
无需额外配置类(默认自动扫描所有Controller)
如果需要自定义配置,只需要添加一个简单的配置类即可,无需处理路径匹配策略的问题,访问路径同样是/swagger-ui/。
内容的提问来源于stack exchange,提问作者WorkWork




