SpringBoot項目下靜態資源無法訪問
在使用自定義mvc配置時,配置類繼承了WebMvcConfigurationSupport導致自動配置類失效,無法自動識別靜態資源目錄


通過查看 WebMvcAutoConfiguration源碼發現
自動配置類只在缺少WebMvcConfigurationSupport的時候生效
如果使用WebConfigurationSupport,則需要以下配置
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/webjars/**")) {
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
if (!registry.hasMappingForPattern("/**")) {
registry.addResourceHandler("/**")
.addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}
}
當然還是推薦通過繼承WebMvcConfigurer的方式來擴展
