1、流程
- 這個類的生效條件是容器中不存在WebMvcConfigurationSupport類型的Bean
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
public class WebMvcAutoConfiguration {
注意,注解的意思是存在這個類型Bean的子類也不行,我們可以通過繼承這個類來覆寫springboot預設自動配置的行為(官方已經不推薦了,官方推薦使用實作接口的方式,不僅僅可以保留預設的行為也可以增加我們的自定義行為)
- springboot自動配置WebMvcAutoConfiguration,這個類中包括了所有mvc相關的配置,靜态資源配置自然在其中。
2、這個類配置了那些内容
- 通過addResourceHandlers方法配置了靜态資源
- 通過welcomePageHandlerMapping配置了首頁的通路
3、思考:預設配置的4個靜态路徑其實已經包括了webjars的配置,而springboot又配置了一個webjars,是否是多餘的?
答:我驗證不配置webjars,隻配置4個預設的靜态路徑,也可以通路到webjars中的靜态檔案,我認為是多餘的。歡迎批評指正。
@Configuration
public class MyWebMvcConfig extends WebMvcConfigurationSupport {
private final String[] CLASSPATH_RESOURCE_LOCATIONS = {"classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/"};
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
/**
* 驗證隻配置4種靜态路徑,不配置webjars,是否也能通路正常通路webjars相關的靜态檔案------->是可以的
* @param registry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
ServletContext servletContext = getServletContext();
// registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/**").addResourceLocations(staticLocations);
}
}