SpringBoot下spring.resources.static-locations未生效

最近因为换了一个从SpringMVC改造过来的SpringBoot开发框架,发现配置了static-locations死活未生效,苦寻未觅。
例如我的配置:

spring:
  resources:
    static-locations: file:D:/static/

最后百度才知道,有可能是MVC的配置中添加了拦截:
找到继承WebMvcConfigurer的配置类

@Configuration
@EnableWebMvc
public class SpringMVCConfig implements WebMvcConfigurer 

查看拦截:

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(new DefaultInterceptorQx())
                .addPathPatterns("/app/**");

    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/", "/index.html");
        registry.addRedirectViewController("/index", "/index.html");
    }

只需要在该类中重写public void addResourceHandlers(ResourceHandlerRegistry registry)方法,并将静态文件地址添加进来即可:

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        try {
            // 或者从配置文件中取static-locations
            registry.addResourceHandler("/**")
                    .addResourceLocations("file:d:\\static\\")
                    .setCachePeriod(31556926);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

参考:https://blog.csdn.net/zxc1310284454/article/details/81127889

你可能感兴趣的:(SpringBoot下spring.resources.static-locations未生效)