SpringBoot学习之路踩坑系列:访问静态资源

众所周知,SpringBoot的静态资源默认路径定义在

org.springframework.boot.autoconfigure.web.ResourceProperties

1 private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
2             "classpath:/META-INF/resources/", "classpath:/resources/",
3             "classpath:/static/", "classpath:/public/" };


不能访问静态资源的原因:

1. 使用@EnableWebMvc:

启用Spring MVC pattern,这时SpringBoot的默认配置就不生效了,静态资源需要放在webapp目录下

2. 配置拦截器

2.1 继承WebMvcConfigurationSupport

在spring boot的自定义配置类继承 WebMvcConfigurationSupport 后,发现自动配置的静态资源路径(classpath:/META/resources/,classpath:/resources/,classpath:/static/,classpath:/public/)不生效。

 WebMvcAutoConfiguration 有如下注解:

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
    WebMvcConfigurerAdapter.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
    ValidationAutoConfiguration.class })

这个注解的意思是在项目类路径中 缺少 WebMvcConfigurationSupport类型的bean时该自动配置类WebMvcAutoConfiguration才会生效,所以继承 WebMvcConfigurationSupport 后需要自己再重写相应的方法。

如果想要使用自动配置生效,又要按自己的需要重写某些方法,比如增加 viewController ,则可以自己的配置类可以继承  WebMvcConfigurerAdapter 这个类。不过在spring5.0版本后这个类被丢弃了 WebMvcConfigurerAdapter  ,虽然还可以用,但是看起来不好 = =。

 重写示例:

@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**")
            .addResourceLocations("classpath:/META-INF/resources/")
            .addResourceLocations("classpath:/resources/")
            .addResourceLocations("classpath:/static/")
            .addResourceLocations("classpath:/public/");
    super.addResourceHandlers(registry);
}
原文地址:https://www.cnblogs.com/frank2015/p/9479609.html