全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-18 8 分钟 ✍️ juanwangdev

Spring MVC 自定义MessageConverter消息转换器

HttpMessageConverter 接口定义了 HTTP 请求体到 Java 对象、Java 对象到响应体的转换规则。

接口定义

Java
public interface HttpMessageConverter<T> {
    boolean canRead(Class<?> clazz, MediaType mediaType);
    boolean canWrite(Class<?> clazz, MediaType mediaType);
    List<MediaType> getSupportedMediaTypes();
    T read(Class<? extends T> clazz, HttpInputMessage inputMessage);
    void write(T t, MediaType contentType, HttpOutputMessage outputMessage);
}

核心方法说明

方法作用
canRead判断是否可读取请求体
canWrite判断是否可写入响应体
read将请求体转为对象
write将对象写入响应体

自定义消息转换器

Java
public class PropertiesMessageConverter extends AbstractGenericHttpMessageConverter<Properties> {

    public PropertiesMessageConverter() {
        super(new MediaType("text", "properties"));
    }

    @Override
    protected Properties readInternal(Class<? extends Properties> clazz,
                                      HttpInputMessage inputMessage) throws IOException {
        Properties props = new Properties();
        props.load(inputMessage.getBody());
        return props;
    }

    @Override
    protected void writeInternal(Properties props, HttpOutputMessage outputMessage)
            throws IOException {
        props.store(outputMessage.getBody(), "Generated by Custom Converter");
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return Properties.class.isAssignableFrom(clazz);
    }
}

注册自定义转换器

Java
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(0, new PropertiesMessageConverter());
    }
}

内置转换器

转换器支持类型
StringHttpMessageConvertertext/plain, text/html
MappingJackson2HttpMessageConverterapplication/json
ByteArrayHttpMessageConverterapplication/octet-stream
FormHttpMessageConverterapplication/x-www-form-urlencoded

使用 extendMessageConverters 追加转换器,configureMessageConverters 会覆盖默认转换器。

要点总结

  • canRead/canWrite 决定转换器是否生效
  • MediaType 匹配 Content-Type 和 Accept 头
  • 转换器顺序影响匹配优先级
  • 可继承 AbstractGenericHttpMessageConverter 简化实现

📝 发现内容有误?点击此处直接编辑

← 上一篇 Spring MVC HandlerInterceptor拦截器
下一篇 → Spring MVC 自定义参数解析器HandlerMethodArgumentResolver
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库