九SpringBoot2核心技术——web开发(静态资源配置原理)

Posted 上善若水

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了九SpringBoot2核心技术——web开发(静态资源配置原理)相关的知识,希望对你有一定的参考价值。

一、静态资源配置原理

  • SpringBoot启动时,默认加载 xxxAutoConfiguration 类 (自动配置类)
    在这里插入图片描述
  • SpringMVC功能的自动配置类 WebMvcAutoConfiguration,生效。
    在这里插入图片描述
@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 {
	...
}
  • 给容器中配了什么?
// Defined as a nested config to ensure WebMvcConfigurer is not read when not
	// on the classpath
	@SuppressWarnings("deprecation")
	@Configuration(proxyBeanMethods = false)
	@Import(EnableWebMvcConfiguration.class)
	@EnableConfigurationProperties({ WebMvcProperties.class,
			org.springframework.boot.autoconfigure.web.ResourceProperties.class, WebProperties.class })
	@Order(0)
	public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ServletContextAware {
		...
	}
  1. 配置文件的相关属性和xxx进行 了绑定。
    WebMvcProperties ——> spring.mvc
    WebProperties ——> spring.web
    ResourceProperties ——> spring.resources
    在这里插入图片描述

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

类:org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter 只有一个有参构造器
在这里插入图片描述

/**
	有参构造器所有参数的值都会从容器中确定
	ResourceProperties resourceProperties 获取和spring.resources绑定的所有值的对象
	WebProperties webProperties	获取和spring.web绑定的所有值的对象
	WebMvcProperties mvcProperties 获取和spring.mvc绑定的所有值的对象
	ListableBeanFactory beanFactory spring的beanFactory
	HttpMessageConverters 找到所有的HttpMessageConverters
	ResourceHandlerRegistrationCustomizer 找到资源处理器的自定义器
	DispatcherServletPath
	ServletRegistrationBean 给应用注册Servlet、Filter...
	
*/
public WebMvcAutoConfigurationAdapter(
		org.springframework.boot.autoconfigure.web.ResourceProperties resourceProperties,
		WebProperties webProperties, WebMvcProperties mvcProperties, ListableBeanFactory beanFactory,
		ObjectProvider<HttpMessageConverters> messageConvertersProvider,
		ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider,
		ObjectProvider<DispatcherServletPath> dispatcherServletPath,
		ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
	this.resourceProperties = resourceProperties.hasBeenCustomized() ? resourceProperties
			: webProperties.getResources();
	this.mvcProperties = mvcProperties;
	this.beanFactory = beanFactory;
	this.messageConvertersProvider = messageConvertersProvider;
	this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
	this.dispatcherServletPath = dispatcherServletPath;
	this.servletRegistrations = servletRegistrations;
	this.mvcProperties.checkConfiguration();
}

1.2、资源处理的默认规则

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
	if (!this.resourceProperties.isAddMappings()) {
		logger.debug("Default resource handling disabled");
		return;
	}
	addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
	addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
		registration.addResourceLocations(this.resourceProperties.getStaticLocations());
		if (this.servletContext != null) {
			ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
			registration.addResourceLocations(resource);
		}
	});
}

src/main/resources/application.yml

server:
  port: 8888
spring:
  web:
    resources:
      add-mappings: false # 禁用所有静态资源规则
// org.springframework.boot.autoconfigure.web.WebProperties 类下的静态内部类
public static class Resources {

	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、欢迎页的处理规则

@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, Resource welcomePage, String staticPathPattern) {
	if (welcomePage != null && "/**".equals(staticPathPattern)) {
		logger.info("Adding welcome page: " + welcomePage);
		setRootViewName("forward:index.html");
	}
	else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
		logger.info("Adding welcome page template: index");
		setRootViewName("index");
	}
}

以上是关于九SpringBoot2核心技术——web开发(静态资源配置原理)的主要内容,如果未能解决你的问题,请参考以下文章

八SpringBoot2核心技术——web开发(静态资源访问)

八SpringBoot2核心技术——web开发(静态资源访问)

十SpringBoot2核心技术——web开发(请求参数处理)

十SpringBoot2核心技术——web开发(请求参数处理)

十四SpringBoot2核心技术——web开发(模块引擎Thymeleaf)_上

十四SpringBoot2核心技术——web开发(模块引擎Thymeleaf)_上