27.1.2. HttpMessageConverters

Spring MVC使用HttpMessageConverter接口转换HTTP请求和响应,合适的默认配置可以开箱即用,例如对象自动转换为JSON(使用Jackson库)或XML(如果Jackson XML扩展可用,否则使用JAXB),字符串默认使用UTF-8编码。

可以使用Spring Boot的HttpMessageConverters类添加或自定义转换类:

  1. import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
  2. import org.springframework.context.annotation.*;
  3. import org.springframework.http.converter.*;
  4. @Configuration
  5. public class MyConfiguration {
  6. @Bean
  7. public HttpMessageConverters customConverters() {
  8. HttpMessageConverter<?> additional = ...
  9. HttpMessageConverter<?> another = ...
  10. return new HttpMessageConverters(additional, another);
  11. }
  12. }

上下文中出现的所有HttpMessageConverter bean都将添加到converters列表,你可以通过这种方式覆盖默认的转换器列表(converters)。