Spring Boot 自动配置 : HttpEncodingAutoConfiguration

概述

自动配置类HttpEncodingAutoConfiguration针对Spring Servlet Web应用,在配置参数spring.http.encoding.enabled不存在或者设置为true时确保bean CharacterEncodingFilter characterEncodingFilter的存在。它的配置过程会利用前缀为spring.http的配置参数项。

HttpEncodingAutoConfiguration另外定义了一个bean LocaleCharsetMappingsCustomizer,这是一个WebServerFactoryCustomizer,它会被webServerFactoryCustomizerBeanPostProcessor使用,基于配置参数spring.http.encoding.mapping配置当前Servlet Web工厂组件ConfigurableServletWebServerFactory

源代码

源代码版本 : spring-boot-autoconfigure-2.1.3.RELEASE

package org.springframework.boot.autoconfigure.web.servlet;

// 忽略 imports

/**
 * EnableAutoConfiguration Auto-configuration for configuring the encoding to use
 * in web applications. 
 */
@Configuration
// 确保前缀为 spring.http 配置项加载到 bean HttpProperties
@EnableConfigurationProperties(HttpProperties.class)
// 仅在当前应用是 Servlet Web 应用时才生效
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
// 仅在类 CharacterEncodingFilter 存在于 classpath 上时才生效
@ConditionalOnClass(CharacterEncodingFilter.class)
// 仅在配置项 spring.http.encoding.enabled 不存在或者设置为 true 时才生效
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)
public class HttpEncodingAutoConfiguration {

	private final HttpProperties.Encoding properties;

	public HttpEncodingAutoConfiguration(HttpProperties properties) {
		this.properties = properties.getEncoding();
	}

    // 定义bean CharacterEncodingFilter characterEncodingFilter
	@Bean
    // 仅在该bean不存在时才定义
	@ConditionalOnMissingBean
	public CharacterEncodingFilter characterEncodingFilter() {
		CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
		filter.setEncoding(this.properties.getCharset().name());
		filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
		filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
		return filter;
	}

    // 定义bean LocaleCharsetMappingsCustomizer localeCharsetMappingsCustomizer
    // 其作用是对当前 ConfigurableServletWebServerFactory 进行配置,使用配置参数中
    // 设置的 spring.http.encoding.mapping
	@Bean
	public LocaleCharsetMappingsCustomizer localeCharsetMappingsCustomizer() {
		return new LocaleCharsetMappingsCustomizer(this.properties);
	}

	private static class LocaleCharsetMappingsCustomizer implements
			WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered {

		private final HttpProperties.Encoding properties;

		LocaleCharsetMappingsCustomizer(HttpProperties.Encoding properties) {
			this.properties = properties;
		}

		@Override
		public void customize(ConfigurableServletWebServerFactory factory) {
			if (this.properties.getMapping() != null) {
				factory.setLocaleCharsetMappings(this.properties.getMapping());
			}
		}

		@Override
		public int getOrder() {
			return 0;
		}

	}

}

参考文章

  • Spring Servlet Web 常用过滤器 : CharacterEncodingFilter

你可能感兴趣的:(Spring,Boot,Spring,Web,Spring,Boot,自动配置)