SpringBoot配置knife4j版的Swagger打开doc.html页面404
项目原因:最近搭建一个新的SpringBoot项目,需要配置Swagger,从其他项目里拷过来knife4j版的Swagger配置文件,结果打开doc.html显示404,如下图:查看日志,错误如下:2020-09-24 17:26:26.518WARN 15524 --- [nio-8003-exec-1] o.s.web.servlet.PageNotFound: No mapping for
项目原因:
最近搭建一个新的SpringBoot项目,需要配置Swagger,从其他项目里拷过来knife4j版的Swagger配置文件,结果打开doc.html显示404,如下图:
查看日志,错误如下:
2020-09-24 17:26:26.518 WARN 15524 --- [nio-8003-exec-1] o.s.web.servlet.PageNotFound : No mapping for GET /doc.html
在官网和其他地方一顿搜,始终没解决。官网推荐的方法是:https://doc.xiaominfo.com/guide/springboot-404.html
因为doc.html是在jar包里的,需要使用资源处理器注册静态资源。
复制代码
@SpringBootApplication
public class SwaggerBootstrapUiDemoApplication implements WebMvcConfigurer{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
修改后的代码
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/systemPictures/**")
.addResourceLocations("file:" + System.getProperty("user.dir")+ File.separator+"uploadFile"+File.separator+"systemPictures"+File.separator);
registry.addResourceHandler("/uploadFile/pluginFiles/logo/**")
.addResourceLocations("file:" + System.getProperty("user.dir")+ File.separator+"uploadFile"+File.separator+"pluginFiles"+File.separator+"logo"+File.separator);
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
// @Override
// protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// String os = System.getProperty("os.name");
//
// //如果是Windows系统
if (os.toLowerCase().startsWith("win")) {
// registry.addResourceHandler("/images/**")
// // /app_file/**表示在磁盘filePathWindow目录下的所有资源会被解析为以下的路径
// .addResourceLocations("file:" + System.getProperty("user.dir")+ File.separator+"uploadFile"+File.separator+"configFiles"+File.separator);
} else { //linux 和mac
registry.addResourceHandler("/app_file/**")
.addResourceLocations("file:" + filePathLinux) ;
}
//
super.addResourceHandlers(registry);
// }
}
}
官方的补充说明是:如果你是使用的老的版本SpringBoot,通过继承WebMvcConfigurationSupport来扩展SpringBoot相关的配置,则把以上配置加在相应的addResourceHandlers方法中即可
在我的WebMvcConfigurer配置类里,加上上面这段代码不好用。
我在翻阅其他文章里,发现一句有用的话,就是
遇到这种情况请先查找,最近有没有添加的类继承了WebMvcConfigurationSupport,则在配置文件在中配置的相关内容会失效,需要重新指定静态资源。
结果我在本地代码一搜,果然有一个类继承了WebMvcConfigurationSupport,我把这个类改成实现WebMvcConfigurer接口,再加上官方推荐的这段代码,访问doc.html恢复正常。
看来问题还是新旧版本SpringBoot配置文件 WebMvcConfigurationSupport类 和 WebMvcConfigurer接口之间有冲突,项目中还是只用一个就好了。
更多推荐
所有评论(0)