springBoot静态资源路径映射配置不生效,浏览器访问为404(addResourceHandler,addResourceLocations springboot-2.6.x不生效)的可能原因

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,已确认addResourceHandleraddResourceLocations所填的值均是正确的

当前使用的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以上版本使用出现问题也可以尝试使用这些方法。

以后遇到配置不生效的时候,得注意一下是不是版本的原因。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值