SpringBoot下静态目录static无法访问

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的方式来扩展

posted @ 2021-06-01 15:33  编程の小白  阅读(1114)  评论(0编辑  收藏  举报