当前位置: 首页 > article >正文

Java --- springboot2的静态资源配置原理

目录

一、静态资源配置原理

1.1、配置类只有一个有参构造器

 1.2、资源处理的默认规则

1.3、欢迎页的处理规则 


一、静态资源配置原理

springboot启动默认加载xxxAutoConfiguration(自动配置)

springmvc功能的自动配置类,生效

 

 

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
      ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {}

给容器中配了什么?

@Configuration(proxyBeanMethods = false)
@Import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {}

配置文件的相关属性和xxx进行绑定。 WebMvcProperties==spring.mvc,ResourceProperties==spring.resources。

1.1、配置类只有一个有参构造器

//有参构造器所有参数的值都会从容器中确定
//ResourceProperties :获取和spring.resources绑定的所有的值的对象
//WebMvcProperties :获取和spring.mvc绑定的所有的值的对象
//ListableBeanFactory :spring的beanFactory
//HttpMessageConverters:找到所有HttpMessageConverters
//ResourceHandlerRegistrationCustomizer:找到资源处理器的自定义器

public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties,
      ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider,
      ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider,
      ObjectProvider<DispatcherServletPath> dispatcherServletPath,
      ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
   this.resourceProperties = resourceProperties;
   this.mvcProperties = mvcProperties;
   this.beanFactory = beanFactory;
   this.messageConvertersProvider = messageConvertersProvider;
   this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
   this.dispatcherServletPath = dispatcherServletPath;
   this.servletRegistrations = servletRegistrations;
}

 1.2、资源处理的默认规则

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
   if (!this.resourceProperties.isAddMappings()) {
      logger.debug("Default resource handling disabled");
      return;
   }
   Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
   CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
   //webjars的规则
   if (!registry.hasMappingForPattern("/webjars/**")) {
      customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/")
            .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
   }
   String staticPathPattern = this.mvcProperties.getStaticPathPattern();
   if (!registry.hasMappingForPattern(staticPathPattern)) {
      customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
            .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
            .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
   }
}

spring:
#  mvc:
#    static-path-pattern: /res/**
  resources:
    static-locations: [classpath:/yaya/]
    add-mappings: false #禁用所有静态资源规则

 

@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;

1.3、欢迎页的处理规则 

//HandlerMapping:处理映射器
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
      FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
   WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
         new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
         this.mvcProperties.getStaticPathPattern());
   welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
   welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
   return welcomePageHandlerMapping;
}
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
      ApplicationContext applicationContext, Optional<Resource> welcomePage, String staticPathPattern) {
//框架底层写死,访问index必须是/**
   if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
      logger.info("Adding welcome page: " + welcomePage.get());
      setRootViewName("forward:index.html");
   }
//调用controller处理index
   else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
      logger.info("Adding welcome page template: index");
      setRootViewName("index");
   }
}

 


http://www.kler.cn/a/15622.html

相关文章:

  • SpringBoot多环境配置的实现
  • 【动手学电机驱动】 STM32-FOC(7)MCSDK Pilot 上位机控制与调试
  • 【Android、IOS、Flutter、鸿蒙、ReactNative 】启动页
  • java 数组 拼接 详解
  • 大数据实验9:Spark安装和编程实践
  • 什么是PostgreSQL,有什么特点
  • 轻量级「行泊一体」爆发前夜!这家智驾Tier1正加码抢占市场
  • VC++运行时库整理
  • Word转PDF:简单步骤,轻松完成!推荐两个实现的方法
  • 为什么重写equals时必须重写hashCode()
  • 【容器化应用程序设计和开发】2.2 Dockerfile 的编写和最佳实践
  • ChatGPT会一直火热下去吗?他会是下一个AR,区块链吗?
  • WRF模式应用:天气预报、模拟分析观测气温、降水、风场、水汽和湿度、土地利用变化、土壤及近地层能量水分通量、土壤、水体、植被等相关气象变量
  • 分治算法(Divide and Conquer)
  • Winform从入门到精通(34)—SaveFileDialog(史上最全)
  • 10.Yarn概述
  • ESP32 ESP-Rainmaker 本地点灯控制Demo测试
  • leetcode19_删除链表的倒数第 N 个结点
  • 【unity】C#协程IEnumerator的使用(上)
  • 【Leetcode每日一刷】动态规划:931. 下降路径最小和
  • Apache Flink
  • Nature Neuroscience:高家红团队首次发布中国人脑连接组计划研究成果及其大数据资源
  • 前端学习笔记:CSS的引入,元素选择器
  • java+mysql医院住院挂号缴费病房信息管理系统
  • 管理后台项目-07-菜单管理和动态展示菜单和按钮
  • API淘宝数据接口