按官方配置集成springdoc-openapi仍返回api-docs 404求助
排查springdoc v3/api-docs 404问题的具体步骤
核对依赖版本与类型
确保使用与SpringBoot版本匹配的springdoc starter依赖:- SpringBoot 3.x需使用
springdoc-openapi-starter-webmvc-ui(或webflux对应starter),而非旧版springdoc-openapi-ui。
示例Maven依赖:
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.2.0</version> </dependency>- SpringBoot 3.x需使用
验证上下文路径配置
你的请求URL包含/springboot-example,需确认:- 是否通过
server.servlet.context-path=springboot-example(Servlet环境)或server.reactive.context-path=springboot-example(Reactive环境)配置了上下文路径。 - 若未配置上下文路径,直接访问
http://localhost:8888/v3/api-docs测试。
- 是否通过
排查拦截器/过滤器拦截
检查自定义的Filter、Interceptor或Security配置,确保已放行springdoc相关路径:- 需排除的路径包括
/v3/api-docs/**、/swagger-ui/**、/swagger-ui.html。
示例Spring Security放行配置:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth .requestMatchers("/v3/api-docs/**", "/swagger-ui/**").permitAll() .anyRequest().authenticated()); return http.build(); }- 需排除的路径包括
检查springdoc配置冲突
- 确认未设置
springdoc.api-docs=false,该配置会禁用API文档端点。 - 若使用SpringBoot 3.x,避免将
spring.mvc.pathmatch.matching-strategy设为ANT_PATH_MATCHER,springdoc默认适配PATH_PATTERN_PARSER,强制旧策略可能导致映射失效。
- 确认未设置
核对启动日志中的端点映射
从启动日志中查找类似如下的映射记录:Mapped "{[/v3/api-docs],methods=[GET],produces=[application/json]}" onto public org.springframework.http.ResponseEntity<...> org.springdoc.webmvc.api.OpenApiWebMvcResource.openapiJson(...)
确保映射的路径与你的请求路径完全匹配(含上下文路径的话需一致)。若日志中映射路径不含上下文路径,说明请求时多余添加了/springboot-example。排查静态资源配置覆盖
若自定义了WebMvcConfigurer的addResourceHandlers方法,避免将/**直接映射到静态资源,否则API端点会被当作静态资源处理。需调整静态资源路径优先级,或排除springdoc的API路径:@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); // 不要添加 registry.addResourceHandler("/**").addResourceLocations(...) 这类覆盖所有路径的配置 }
内容的提问来源于stack exchange,提问作者Todd347
相关产品推荐
相关产品推荐

