为何添加@EnableWebMvc会导致Spring Boot无法找到静态资源?
Spring Boot加@EnableWebMvc后静态资源丢失的问题解析
一、问题根源
Spring Boot默认通过WebMvcAutoConfiguration自动配置了静态资源映射,会把classpath:/static/、classpath:/public/、classpath:/resources/这些目录下的静态资源开放访问。但一旦你给配置类加上@EnableWebMvc注解,这个自动配置就会被禁用——因为@EnableWebMvc导入的DelegatingWebMvcConfiguration继承了WebMvcConfigurationSupport,而WebMvcAutoConfiguration上有@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)的条件注解,只要存在WebMvcConfigurationSupport类型的Bean,自动配置就不生效。原来的静态资源映射规则没了,自然就找不到静态文件了。
二、解决方法
两种选择:
- 去掉@EnableWebMvc:如果你的需求只是添加自定义参数解析器,不用加这个注解,直接实现
WebMvcConfigurer就行,Spring Boot的自动配置会保留,静态资源也能正常访问。 - 手动配置静态资源映射:如果必须加
@EnableWebMvc,就在WebConfig里重写addResourceHandlers方法,把默认的静态资源路径加回去:
@Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Autowired private UserArgumentResolver userArgumentResolver; @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { resolvers.add(userArgumentResolver); } // 手动添加静态资源映射,恢复Spring Boot默认规则 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/") .addResourceLocations("classpath:/public/") .addResourceLocations("classpath:/resources/") .addResourceLocations("classpath:/META-INF/resources/"); } }
另外还要修正login.html里的背景图写法,原来的background:url("@{/img/bg.jpg}")Thymeleaf不会解析,要改成内联写法:
<style type="text/css" th:inline="css"> html,body{ height:100%; width:100%; } body{ background:url([[@{/img/bg.jpg}]]) no-repeat; background-size:100% 100%; padding-top:100px; } </style>
这就是错误日志里出现/login/@%7B/img/bg.jpg%7D请求的原因——Thymeleaf没解析表达式,直接把字符串当路径了。
三、为什么教程里加@EnableWebMvc能正常运行?
无非这几种情况:
- 教程的
WebConfig里已经重写了addResourceHandlers,手动配置了静态资源映射; - 教程用的Spring Boot版本和你不同,早期版本的自动配置逻辑有差异;
- 教程的静态资源放在了其他被映射的路径,或者有其他配置类处理了静态资源访问。
内容的提问来源于stack exchange,提问作者meimaymay
相关产品推荐
相关产品推荐

