spring boot.2x 自定義WebConfig 後靜態資源不能訪問

spring boot.2x 自定義WebConfig 後靜態資源不能訪問

1.現象

在使用SpringBoot2.x的時,自定義WebConfigurer時繼承從WebMvcConfigurerAdapter改爲了WebMvcConfigurationSupport ,然而發現只要繼承 WebMvcConfigurationSupport而且將文件加入配置,在yml中配置路徑的相關內容會失效,就會遇到靜態資源沒法訪問的問題。java

2.緣由及解決方法

這是由於WebMvc的自動配置都在WebMvcAutoConfiguration類中,可是類中有這個註解@ConditionalOnMissingBean({WebMvcConfigurationSupport.class}),意思是一旦在容器中檢測到WebMvcConfigurationSupport這個類,WebMvcAutoConfiguration類中的配置都不生效。因此一旦咱們本身寫的配置類繼承了WebMvcConfigurationSupport,至關於容器中已經有了WebMvcConfigurationSupport,因此默認配置都不會生效,都得本身在配置文件中配置。spring

靜態資源映射配置ide

@Component
class WebConfigurer extends WebMvcConfigurationSupport {
	/**
	* 能夠分別配置多個靜態路徑的映射規則,spring會自動調用add()方法進行規則添加.
	*/
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //靜態目錄映射
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/META-INF/resources/")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/");
        //特定靜態目錄映射
        registry.addResourceHandler("/files/**")
                .addResourceLocations("file:///"+bootdoConfig.getUploadPath());
        super.addResourceHandlers(registry);
    }
}
相關文章
相關標籤/搜索