Spring Boot中修改Swagger UI基础路径以解决路由冲突
解决Swagger UI与通配符路由冲突的路径修改方案
我之前也碰到过一模一样的问题——根路径的/{coll}通配符会匹配所有根目录下的请求,直接把Swagger默认的/swagger-ui.html给拦截了。下面针对不同版本的Springfox给你具体的解决步骤:
针对Springfox 2.x(Swagger 2)
你需要同时配置Swagger的基础路径映射,以及把Swagger的静态资源转到/docs路径下:
@Configuration @EnableSwagger2 public class SwaggerConfig { // 配置Swagger API文档的基础路径 @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.your.project.package")) // 替换成你的接口包路径 .paths(PathSelectors.any()) .build() .pathMapping("/docs"); // 将API文档的基础路径设为/docs } // 配置静态资源映射,让Swagger UI能在/docs路径下访问 @Configuration public class SwaggerResourceConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 映射Swagger UI页面 registry.addResourceHandler("/docs/swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); // 映射Swagger UI依赖的webjars资源 registry.addResourceHandler("/docs/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } } }
配置完成后,你就可以通过http://localhost:8080/docs/swagger-ui.html访问Swagger UI了,而/{coll}的路由只会匹配根路径下的请求,不会干扰/docs开头的路径。
针对Springfox 3.x(OpenAPI 3)
Springfox 3.x的默认路径和资源结构有变化,需要调整一下配置:
@Configuration @EnableOpenApi public class SwaggerConfig { // 配置OpenAPI基础信息 @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info() .title("你的API文档") .version("v1.0") .description("接口文档描述")); } // 配置资源映射和页面跳转 @Configuration public class SwaggerResourceConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 映射Swagger UI的静态资源到/docs路径 registry.addResourceHandler("/docs/swagger-ui/**") .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/") .resourceChain(false); // 映射OpenAPI的JSON文档路径 registry.addResourceHandler("/docs/v3/api-docs/**") .addResourceLocations("classpath:/META-INF/resources/"); } // 配置页面跳转,让/docs/swagger-ui.html重定向到实际的UI入口 @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/docs/swagger-ui.html") .setViewName("forward:/docs/swagger-ui/index.html"); } } }
额外注意事项(Spring Boot 2.6+)
如果你的Spring Boot版本是2.6及以上,需要在application.properties或application.yml中添加以下配置,解决Springfox和新路径匹配策略的兼容性问题:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
这样配置后,访问http://localhost:8080/docs/swagger-ui.html就能正常打开Swagger UI,同时不会和你的/{coll}路由冲突了。
内容的提问来源于stack exchange,提问作者Shashika
相关产品推荐
相关产品推荐

