Spring Boot引入swagger-ui 后swagger-ui.html无法访问404

最近给graphserver增加swagger,记录下过程与问题解决。

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务,后端集成下Swagger,然后就可以提供一个在线文档地址给前端同学。

引入 Swagger#

pom中加入相关配置:

Copy
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>

增加Swagger2Config, 添加@EnableSwagger2,可以通过定义Docket bean实现自定义。

Copy
@Configuration @EnableSwagger2 @Profile("swagger") @ComponentScan("xxx.controller") public class Swagger2Config { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .enable(true) .select() .apis(RequestHandlerSelectors.basePackage("xxx.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("XXX Rest Server") .description("XXXRest接口") .contact(new Contact("contract", "url", "email")) .version("1.0") .build(); } }

swagger-ui.html 404问题#

项目中有web配置,因此怀疑是这些配置影响了,搜索下发现这位仁兄有类似经历:https://www.cnblogs.com/pangguoming/p/10551895.html

于是在WebMvcConfig 配置中,override addResourceHandlers

Copy
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("classpath:/static/"); registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); }

搞定收工。

延伸阅读#

server端有了swagger,前端如何更优先的调用?

参见:Vue 使用typescript, 优雅的调用swagger API,笔者提供了一个开源npm库,可以为前端生成调用axios调用代码。

参考#

关注作者

欢迎关注作者微信公众号, 一起交流软件开发:欢迎关注作者微信公众号

posted @   JadePeng  阅读(18257)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示
CONTENTS