MENU

SpringBoot配置WebMvcConfigurationSupport导致静态资源无法访问的问题

March 22, 2020 • 笔记

问题

SpringBoot项目中无法访问resource/static目录下的文件

查找原因

经过排查和查找资料,发现是由于配置跨域时重写了WebMvcConfigurationSupport导致覆盖了默认的配置

@Configuration
public class CorsConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        super.addCorsMappings(registry);
        registry.addMapping("/**")
                .allowedOrigins("*");
    }
}

解决方法

重写addResourceHandlers方法,增加默认配置静态路径

@Configuration
public class CorsConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/");
        super.addResourceHandlers(registry);
    }

    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        super.addCorsMappings(registry);
        registry.addMapping("/**")
                .allowedOrigins("*");
    }
}
Archives QR Code Tip
QR Code for this page
Tipping QR Code