Spring Boot Thymeleaf页面可访问但js/css静态资源无法加载
问题根因
- 自定义配置类
WebConfig上标注的@EnableWebMvc注解,会直接关闭Spring Boot对Spring MVC的全部自动配置逻辑。 - Spring Boot默认的静态资源访问规则,由MVC自动配置类
WebMvcAutoConfiguration提供:默认会把classpath:/static/、classpath:/public/、classpath:/resources/、classpath:/META-INF/resources/四个目录下的所有资源,映射到/**路径下供外部访问。@EnableWebMvc触发自动配置失效后,这套静态资源映射规则不再生效,导致所有css、js请求无法被解析。 - 同时
WebConfig上的@ComponentScan属于冗余配置:启动类AlgorithmVisualizerApplication本身就会扫描所在包(com.visualizer.web)及所有子包下的组件,当前配置类位于com.visualizer.web.config包下,已在默认扫描范围内,不需要额外添加组件扫描注解。
解决方案
方案一(推荐,适配绝大多数场景)
直接移除WebConfig上的@EnableWebMvc和冗余的@ComponentScan注解,修改后的完整配置代码如下:
package com.visualizer.web.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("test"); } }
说明:实现
WebMvcConfigurer接口本身不会关闭Spring Boot的MVC自动配置,仅用于扩展自定义MVC规则,只有@EnableWebMvc才会触发自动配置的关闭。修改后Spring Boot默认的静态资源映射规则会自动生效,static目录下的css、js资源即可正常加载。
方案二(需保留@EnableWebMvc的场景使用)
如果业务上必须保留@EnableWebMvc,则需要手动在配置类中重写addResourceHandlers方法,补全静态资源映射规则,修改后的完整配置代码如下:
package com.visualizer.web.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("test"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 对齐Spring Boot默认的static目录静态资源映射规则 registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/"); } }
修改配置后重启应用,即可正常访问HTML页面及关联的css、js静态资源。
内容的提问来源于stack exchange,提问作者456c526f
相关产品推荐
相关产品推荐

