Spring Boot内置的自动配置功能——http编码

一 点睛

自动配置要满足两个条件:

  • 能配置CharacterEncodingFilter这个Bean
  • 能配置encoding和forceEncoding这两个参数

二 HttpEncodingProperties源码解读

Spring Boot的自动配置是基于类型安全配置,在application.properties直接配置可以覆盖该配置类的默认值。

源码分析如下:

//在application.properties配置的时候前缀是spring.http.encoding
@ConfigurationProperties(prefix = "spring.http.encoding")
public class HttpEncodingProperties {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    //编码默认配置是UTF-8,若修改可使用spring.http.encoding.charset=编码
    private Charset charset = DEFAULT_CHARSET;

    //设置forceEncoding,默认为true,若修改可使用spring.http.encoding.force=false
    private boolean force = true;

    public Charset getCharset() {
        return this.charset;
    }

    public void setCharset(Charset charset) {
        this.charset = charset;
    }

    public boolean isForce() {
        return this.force;
    }

    public void setForce(boolean force) {
        this.force = force;
    }

}

三 HttpEncodingAutoConfiguration源码解读

@Configuration
//开启配置属性的注入,通过@EnableConfigurationProperties声明
@EnableConfigurationProperties(HttpEncodingProperties.class)  
//当CharacterEncodingFilter在类路径的条件下
@ConditionalOnClass(CharacterEncodingFilter.class)
//当spring.http.encoding=enabled的情况下,如果没有设置则默认为true,即条件符合
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)
public class HttpEncodingAutoConfiguration {

    //注入HttpEncodingProperties属性
    @Autowired
    private HttpEncodingProperties httpEncodingProperties;

    //配置CharacterEncodingFilter这个Bean
    @Bean
    //容器中没有CharacterEncodingFilter这个Bean才会执行下面代码
    @ConditionalOnMissingBean(CharacterEncodingFilter.class)
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.httpEncodingProperties.getCharset().name());
        filter.setForceEncoding(this.httpEncodingProperties.isForce());
        return filter;
    }

}

四 参考

https://blog.csdn.net/wangmx1993328/article/details/81032846

你可能感兴趣的:(Spring,Boot)