从Springfox迁移至Springdoc遇406错误:Swagger-UI无法正常访问
解决Spring Boot 1.5.x迁移Springdoc时Swagger UI 406错误的方案
问题核心是/swagger-ui/index.html请求被自定义的/{param1}/{param2}通配符控制器拦截,该控制器仅返回application/json类型,而Swagger UI需要HTML资源,因此触发HttpMediaTypeNotAcceptableException。以下是具体解决方法:
1. 调整自定义控制器路由,避免路径冲突
给自定义控制器的路由添加更具体的前缀,避免与Swagger UI的路径匹配:
@RestController // 添加/api前缀,避免拦截/swagger-ui开头的请求 @RequestMapping(value = "/api/{param1}/{param2}", produces = MediaType.APPLICATION_JSON_VALUE) public class CustomController { @GetMapping public ResponseEntity<?> handleRequest(@PathVariable String param1, @PathVariable String param2) { // 原有业务逻辑 } }
如果无法修改前缀,可通过正则限制param1不能为swagger-ui:
@RequestMapping(value = "/{param1:[^swagger-ui]+}/{param2}", produces = MediaType.APPLICATION_JSON_VALUE)
2. 显式配置Swagger UI资源映射优先级
创建WebMvc配置类,让DispatcherServlet优先处理Swagger UI的静态资源:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebMvcSwaggerConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 优先映射Swagger UI的静态资源 registry.addResourceHandler("/swagger-ui/**") .addResourceLocations("classpath:/META-INF/resources/webjars/springdoc-openapi-ui/") .setCachePeriod(0); // 保留原有资源配置 super.addResourceHandlers(registry); } }
3. 确认Springdoc配置正确
在application.properties中启用并配置Swagger UI:
springdoc.swagger-ui.enabled=true springdoc.swagger-ui.path=/swagger-ui.html springdoc.api-docs.path=/v3/api-docs
同时确保依赖引入正确(Maven示例):
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.6.14</version> </dependency>
内容的提问来源于stack exchange,提问作者Bharata
相关产品推荐
相关产品推荐

