CentOS 上 Swagger 启动失败常见根因与排查路径
一 常见根因概览
二 快速排查步骤
firewall-cmd --zone=public --add-port=8080/tcp --permanent && firewall-cmd --reload。三 典型场景与修复要点
| 症状 | 可能原因 | 修复要点 |
|---|---|---|
| 启动报错:Failed to start bean ‘documentationPluginsBootstrapper’ | Spring Boot 2.6+ 路径匹配策略与 Springfox 不兼容 | 在 application.yml 添加:spring: mvc: pathmatch: matching-strategy: ant_path_matcher |
| 访问 /swagger/v1/swagger.json 报 500,日志提示 Ambiguous HTTP method for action | 方法未标注 @HttpGet/@HttpPost 或误将 public 方法暴露 | 给方法补上 @HttpGet/@HttpPost;将不应暴露的方法改为 private |
| 启动或扫描时报 [scanDocumentation,98] - Unable to scan documentation context default | GET 请求包含 List 等复杂入参 | 删除 List 参数或改为 POST 请求 |
| 页面空白或 Failed to load API definition | 文档 JSON 获取失败、路径错误或代理未转发 | 用 curl 验证 /v2/api-docs 或 /v3/api-docs;修正 Nginx location 与后端 context-path |
| 401/403 或 CORS 错误 | Spring Security 未放行或 CORS 策略过严 | 放行 /swagger-ui/、/v3/api-docs/;配置全局 CORS 允许 Authorization 头 |
| 启动日志出现 NumberFormatException: For input string: “” | @ApiModelProperty(example=) 为空 | 为数值类型字段补全 example 值(如 example = "0") |
四 配置示例
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
.anyRequest().authenticated();
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/3.52.5/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
}
}
sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent
sudo firewall-cmd --reload
docker pull swaggerapi/swagger-ui:v4.15.5
docker run -d -p 38081:8080 \
-e SWAGGER_FILE=/app/swagger.yaml \
swaggerapi/swagger-ui:v4.15.5