springBoot静态资源路径映射配置不生效(addResourceHandler,addResourceLocations springboot-2.6.x不生效)的可能原因
静态资源路径映射配置的大致代码如下:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private static String localhostPath = "D:\\学习资料\\学习笔记\\springboot+vue+elementUI-个人博客\\images\\";
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("虚拟路径").addResourceLocations("file:本地资源路径");
registry.addResourceHandler("/image/**").addResourceLocations("file:" + localhostPath);
}
}
随后发现配置不生效,使用浏览器打开都是404,已确认addResourceHandler和addResourceLocations所填的值均是正确的
当前使用的springboot版本是2.6.7版本
随后将springboot依赖修改成2.5.8版本后,静态资源映射就生效了
Springboot-2.6.7版本无效,springboot- 2.5.8版本有效
因此可能是相关的spring的源代码修改了
后咨询前辈@码农小胖哥
码农小胖哥的博客_CSDN博客-Spring Security与OAuth2,java,spring security领域博主
知道是Springboot-2.6.x所使用到的spring mvc-5.3.x 默认的路径匹配策略改变了:
Spring MVC 处理程序映射匹配请求路径的默认策略已从 AntPathMatcher 更改为PathPatternParser。
Actuator端点现在也使用基于 PathPattern 的 URL 匹配。需要注意的是,Actuator端点的路径匹配策略无法通过配置属性进行配置。
如果需要将默认切换回 AntPathMatcher,可以将 spring.mvc.pathmatch.matching-strategy 设置为 ant-path-matcher,比如下面这样:
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
加上这一配置后,
Springboot-2.6.7的静态资源路径映射也可以正常使用了。
解决方法总结:
1.修改springboot版本为低版本,如2.5.x
2.添加配置 spring.mvc.pathmatch.matching-strategy=ant-path-matcher
3.使用低版本的spring-mvc依赖
knife4j(swagger) 在springboot- 2.6以上版本使用出现问题也可以尝试使用这些方法。
以后遇到配置不生效的时候,得注意一下是不是版本的原因。