現象
當用戶在自己的spring boot main class上面顯式使用了 @EnableWebMvc
,發現原來的放在 src/main/resources/static
目錄下面的靜態資源訪問不到了。
@SpringBootApplication
@EnableWebMvc
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
比如在用戶代碼目錄 src/main/resources
裏有一個 hello.txt
的資源。訪問 http://localhost:8080/hello.txt
返回的結果是404:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Jun 01 11:39:41 CST 2017
There was an unexpected error (type=Not Found, status=404).
No message available
靜態資源訪問失敗原因
@EnableWebMvc
的實現
那麼爲什麼用戶顯式配置了 @EnableWebMvc
,spring boot訪問靜態資源會失敗?
我們先來看下 @EnableWebMvc
的實現:
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
/**
* A subclass of {@code WebMvcConfigurationSupport} that detects and delegates
* to all beans of type {@link WebMvcConfigurer} allowing them to customize the
* configuration provided by {@code WebMvcConfigurationSupport}. This is the
* class actually imported by {@link EnableWebMvc @EnableWebMvc}.
*
* @author Rossen Stoyanchev
* @since 3.1
*/
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
可以看到 @EnableWebMvc
引入了 WebMvcConfigurationSupport
,是spring mvc 3.1裏引入的一個自動初始化配置的 @Configuration
類。
spring boot裏的靜態資源訪問的實現
再來看下spring boot裏是怎麼實現對 src/main/resources/static
這些目錄的支持。
主要是通過 org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration
來實現的。
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
WebMvcConfigurerAdapter.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
可以看到 @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
裏。
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" };
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };
private static final String[] RESOURCE_LOCATIONS;
static {
RESOURCE_LOCATIONS = new String[CLASSPATH_RESOURCE_LOCATIONS.length
+ SERVLET_RESOURCE_LOCATIONS.length];
System.arraycopy(SERVLET_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, 0,
SERVLET_RESOURCE_LOCATIONS.length);
System.arraycopy(CLASSPATH_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS,
SERVLET_RESOURCE_LOCATIONS.length, CLASSPATH_RESOURCE_LOCATIONS.length);
}
然後在 WebMvcAutoConfigurationAdapter
裏會初始始化相關的ResourceHandler。
//org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter
@Configuration
@Import({ EnableWebMvcConfiguration.class, MvcValidatorRegistrar.class })
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter {
private static final Log logger = LogFactory
.getLog(WebMvcConfigurerAdapter.class);
private final ResourceProperties resourceProperties;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Integer cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(
registry.addResourceHandler("/webjars/**")
.addResourceLocations(
"classpath:/META-INF/resources/webjars/")
.setCachePeriod(cachePeriod));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(
registry.addResourceHandler(staticPathPattern)
.addResourceLocations(
this.resourceProperties.getStaticLocations())
.setCachePeriod(cachePeriod));
}
}
用戶可以自己修改這個默認的靜態資源目錄,但是不建議,因爲很容易引出奇怪的404問題。