Spring Reactive中RouterFunction.resources()无法访问Web资源的解决方法
Spring WebFlux Router Functions 静态资源配置问题
问题现象
部署提供的代码后,访问网站根路径可正常获取index.html,但页面引用的assets、fonts、img目录下的静态资源全部返回404错误。
问题原因
- 资源路径配置错误:静态资源实际存放在Jar包的
static目录下,但配置中ClassPathResource直接指向根路径的assets/、fonts/、img/,Spring无法定位到正确的资源位置。 - 路由匹配顺序冲突:最后一条
RouterFunctions.resources("/**", new ClassPathResource("/"))会匹配所有请求,导致前面定义的具体资源路由被覆盖,无法生效。
修正方案
1. 修正静态资源路由配置
调整resourceRouter的资源路径指向,确保ClassPathResource指向static目录下的对应资源,同时移除兜底的/**路由避免冲突:
@Bean public RouterFunction<ServerResponse> resourceRouter() { return RouterFunctions.resources("/assets/**", new ClassPathResource("static/assets/")) .and(RouterFunctions.resources("/fonts/**", new ClassPathResource("static/fonts/"))) .and(RouterFunctions.resources("/img/**", new ClassPathResource("static/img/"))); }
2. 优化根路径index.html的加载方式
无需手动读取文件内容,直接通过资源路由的方式返回index.html,代码更简洁且避免IO异常处理:
@Bean public RouterFunction<ServerResponse> indexRouter() { return route(GET("/"), request -> ServerResponse.ok() .contentType(MediaType.TEXT_HTML) .bodyValue(new ClassPathResource("static/index.html")) ); }
3. 确认页面资源引用路径
确保index.html中资源的相对引用路径正确,比如使用assets/css/main.css、img/logo.png这类路径,浏览器会以网站根路径为基准发起请求,匹配我们配置的路由规则。
内容的提问来源于stack exchange,提问作者Oliver Watkins
相关产品推荐
相关产品推荐

