SpringBoot 静态资源类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34579060/article/details/89511800

SpringBoot 对于SpringMVC的自动化配置都在  WebMvcAutoConfiguration类中。

WebMvcAutoConfiguration类

有个静态内部类 WebMvcAutoConfigurationAdapter 实现了

WebMvcConfigurer 的addResourceHandlers 用来配置静态资源过滤。

if (!registry.hasMappingForPattern(staticPathPattern)) {
   customizeResourceHandlerRegistration(
         registry.addResourceHandler(staticPathPattern)
               .addResourceLocations(getResourceLocations(
                     this.resourceProperties.getStaticLocations()))
               .setCachePeriod(getSeconds(cachePeriod))
               .setCacheControl(cacheControl));
}

静态资源位置定义:

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {

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

   /**
    * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
    * /resources/, /static/, /public/].
    */
   private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

   public String[] getStaticLocations() {
      return this.staticLocations;
   }

   public void setStaticLocations(String[] staticLocations) {
      this.staticLocations = appendSlashIfNecessary(staticLocations);
   }

   private String[] appendSlashIfNecessary(String[] staticLocations) {
      String[] normalized = new String[staticLocations.length];
      for (int i = 0; i < staticLocations.length; i++) {
         String location = staticLocations[i];
         normalized[i] = location.endsWith("/") ? location : location + "/";
      }
      return normalized;
   }

猜你喜欢

转载自blog.csdn.net/qq_34579060/article/details/89511800
今日推荐