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);
    }
}
相关文章
相关标签/搜索