springdoc-openapi中ExampleObject外部示例文件Base Path修改问题
解决Springdoc Swagger UI加载外部示例文件的Base Path问题
当你用org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.3集成Swagger,通过@ExampleObject的externalValue指定resources/static下的JSON作为外部示例时,Swagger UI默认会给路径加上/v3/前缀,导致文件加载出错。可以用下面几种方法修改或移除这个Base Path:
1. 修改Springdoc静态资源前缀配置
直接在配置文件里指定Swagger UI加载静态资源的前缀,把默认的/v3/去掉:
- application.properties:
springdoc.swagger-ui.static-resources-prefix=/
- application.yml:
springdoc: swagger-ui: static-resources-prefix: /
配置后,@ExampleObject(externalValue = "/static/Response.json")就会被Swagger UI解析为根路径下的/static/Response.json,不再带/v3/前缀。
2. 直接写根路径的示例地址
不想改全局配置的话,直接在@ExampleObject里用绝对根路径:
@ApiResponse(responseCode = "200", description = "成功响应", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = @ExampleObject(externalValue = "/static/Response.json")))
只要Spring Boot默认的静态资源映射没被修改(默认会把resources/static下的文件映射到/static/**路径),这个文件就能通过http://你的域名/static/Response.json直接访问,Swagger UI自然能加载到。
3. 自定义静态资源映射(兜底方案)
如果上面两种方法都不生效,手动配置静态资源映射规则:
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 把resources/static下的文件映射到根路径,直接访问/Response.json就能拿到文件 registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/"); // 或者保留原有/static/**的映射,确保路径对应 // registry.addResourceHandler("/static/**") // .addResourceLocations("classpath:/static/"); } }
这时@ExampleObject可以写成externalValue = "/Response.json"或者/static/Response.json,根据你配置的映射规则来就行。
内容的提问来源于stack exchange,提问作者crimson589
相关产品推荐
相关产品推荐

