现象
当用户在自己的spring boot main class上面显式使用了@EnableWebMvc,发现原来的放在 src/main/resources/static 目录下面的静态资源访问不到了。
1 |
|
比如在用户代码目录src/main/resources里有一个hello.txt的资源。访问 http://localhost:8080/hello.txt 返回的结果是404:
1 | Whitelabel Error Page |
静态资源访问失败原因
@EnableWebMvc的实现
那么为什么用户显式配置了@EnableWebMvc,spring boot访问静态资源会失败?
我们先来看下@EnableWebMvc的实现:
1 | (DelegatingWebMvcConfiguration.class) |
1 | /** |
可以看到@EnableWebMvc 引入了 WebMvcConfigurationSupport,是spring mvc 3.1里引入的一个自动初始化配置的@Configuration 类。
spring boot里的静态资源访问的实现
再来看下spring boot里是怎么实现对src/main/resources/static这些目录的支持。
主要是通过org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration来实现的。
1 |
|
可以看到 @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) ,这个条件导致spring boot的WebMvcAutoConfiguration不生效。
总结下具体的原因:
- 用户配置了
@EnableWebMvc - Spring扫描所有的注解,再从注解上扫描到
@Import,把这些@Import引入的bean信息都缓存起来 - 在扫描到
@EnableWebMvc时,通过@Import加入了DelegatingWebMvcConfiguration,也就是WebMvcConfigurationSupport - spring再处理
@Conditional相关的注解,判断发现已有WebMvcConfigurationSupport,就跳过了spring bootr的WebMvcAutoConfiguration
所以spring boot自己的静态资源配置不生效。
其实在spring boot的文档里也有提到这点: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration
- If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurerAdapter, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing such components.
Spring Boot ResourceProperties的配置
在spring boot里静态资源目录的配置是在ResourceProperties里。
1 | (prefix = "spring.resources", ignoreUnknownFields = false) |
然后在 WebMvcAutoConfigurationAdapter里会初始始化相关的ResourceHandler。
1 | //org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter |
用户可以自己修改这个默认的静态资源目录,但是不建议,因为很容易引出奇怪的404问题。