参考文献1
参考文献2
想知道@EnableWebMvc为什么会是静态资源失效首先要了解一下这个注解
springboot中默认是约定大于配置的,如果你又有配置类又有配置文件的情况下默认先加载配置类
引入了这样一个类DelegatingWebMvcConfiguration,通过@Bean注册了和<mvc:annotation-driven/>一样的组件,RequestMappingHandlerMapping、RequestMappingHandlerAdatper、HandlerExceptionResolver等等,只要有个Spring管理的bean继承WebMvcConfigurer或WebMvcConfigurerAdapter,重写方法即可自定义<mvc:annotation-driven/>.
其实@EnableWebMvc == @Import({DelegatingWebMvcConfiguration.class})
失效原因
- Spring扫描所有的注解,再从注解上扫描到@Import,把这些@Import引入的bean信息都缓存起来
- 在扫描到@EnableWebMvc时,通过@Import加入了 DelegatingWebMvcConfiguration,也就是WebMvcConfigurationSupport
- spring在处理@Conditional相关的注解,判断发现已有WebMvcConfigurationSupport,就跳过了spring bootr的WebMvcAutoConfiguration
解决方案
- 删掉此注解
- 手动配置静态资源路径
- 在该注解类上添加默认的资源放行路径
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(“/**”)
.addResourceLocations(“classpath:/resources/”)
.addResourceLocations(“classpath:/static/”)
.addResourceLocations(“classpath:/public/”);
WebMvcConfigurer.super.addResourceHandlers(registry);
}
- 在yml中配置
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/