聊聊springboot中如何自定义消息转换器

 更新时间:2025年08月15日 12:15:59   作者:白衣神棍  
SpringBoot通过HttpMessageConverter处理HTTP数据转换,支持多种媒体类型,接下来通过本文给大家介绍springboot中如何自定义消息转换器,感兴趣的朋友一起看看吧

Spring Boot 中的消息转换器(HttpMessageConverter)是处理 HTTP 请求和响应数据格式转换的核心组件,负责将 HTTP 请求体中的数据转换为 Java 对象,或将 Java 对象转换为 HTTP 响应体的数据。

核心接口

public interface HttpMessageConverter<T> {
    boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);
    boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);
    List<MediaType> getSupportedMediaTypes();
    default List<MediaType> getSupportedMediaTypes(Class<?> clazz) {
        return !this.canRead(clazz, (MediaType)null) && !this.canWrite(clazz, (MediaType)null) ? Collections.emptyList() : this.getSupportedMediaTypes();
    }
    T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException;
    void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException;
}

getSupportedMediaTypes 定义支持的媒体类型(如:application/json)

canRead/canWrite:判断是否支持读写操作

read/write:执行具体的数据转换逻辑

springboot默认提供的转换器

Spring Boot 自动配置了以下常用消息转换器:

  1. StringHttpMessageConverter - 处理文本数据
  2. MappingJackson2HttpMessageConverter - 处理 JSON 数据(使用 Jackson)
  3. FormHttpMessageConverter - 处理表单数据
  4. ByteArrayHttpMessageConverter - 处理字节数组
  5. ResourceHttpMessageConverter - 处理资源文件
  6. Jaxb2RootElementHttpMessageConverter - 处理 XML(使用 JAXB)
  7. AllEncompassingFormHttpMessageConverter - 增强的表单处理器

springboot在启动的时候就会自动注册上述默认的转换器,有请求进来的时候会根据请求的accept和响应的Content-Type,选择匹配的转换器,若多个转换器都支持,则按注册顺序优先。

如何自定义消息转换器

比如自定义个fastjson转换器

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.NonNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class FastJsonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
    private final FastJsonConfig fastJsonConfig = new FastJsonConfig();
    public FastJsonHttpMessageConverter() {
        // 支持多种媒体类型
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(new MediaType("application", "*+json"));
        setSupportedMediaTypes(supportedMediaTypes);
        // 配置FastJson
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonConfig.setCharset(StandardCharsets.UTF_8);
    }
    @Override
    protected boolean supports(@NonNull Class<?> clazz) {
        return true; // 支持所有类型
    }
    @Override
    protected Object readInternal(
            @NonNull Class<?> clazz,
            @NonNull HttpInputMessage inputMessage
    ) throws IOException, HttpMessageNotReadableException {
        try (InputStream in = inputMessage.getBody()) {
            return JSON.parseObject(
                    in,
                    fastJsonConfig.getCharset(),
                    clazz,
                    fastJsonConfig.getFeatures()
            );
        } catch (Exception e) {
            throw new HttpMessageNotReadableException(
                    "JSON parse error: " + e.getMessage(),
                    inputMessage
            );
        }
    }
    @Override
    protected void writeInternal(
            @NonNull Object object,
            @NonNull HttpOutputMessage outputMessage
    ) throws IOException, HttpMessageNotWritableException {
        try (OutputStream out = outputMessage.getBody()) {
            JSON.writeTo(
                    out,
                    object,
                    fastJsonConfig.getCharset(),
                    fastJsonConfig.getFeatures(),
                    fastJsonConfig.getFilters(),
                    fastJsonConfig.getDateFormat(),
                    JSON.DEFAULT_GENERATE_FEATURE,
                    fastJsonConfig.getWriterFeatures()
            );
        } catch (Exception e) {
            throw new HttpMessageNotWritableException(
                    "JSON write error: " + e.getMessage(),
                    e
            );
        }
    }
    public FastJsonConfig getFastJsonConfig() {
        return fastJsonConfig;
    }
    public void setFastJsonConfig(FastJsonConfig fastJsonConfig) {
        this.fastJsonConfig.setDateFormat(fastJsonConfig.getDateFormat());
        this.fastJsonConfig.setCharset(fastJsonConfig.getCharset());
        this.fastJsonConfig.setFeatures(fastJsonConfig.getFeatures());
        this.fastJsonConfig.setReaderFeatures(fastJsonConfig.getReaderFeatures());
        this.fastJsonConfig.setWriterFeatures(fastJsonConfig.getWriterFeatures());
        this.fastJsonConfig.setFilters(fastJsonConfig.getFilters());
    }
}

注册自定义的消息转换器 

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class FastJsonWebConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 创建FastJson消息转换器
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        // 可以在这里进一步配置FastJson
        // fastJsonConverter.getFastJsonConfig().setDateFormat("yyyy-MM-dd");
        // 将FastJson转换器添加到转换器列表的最前面
        converters.add(0, fastJsonConverter);
    }
}

注意这里优先级的问题,要把fastjson的放前面,这样才会优先走咱自定义的fastjson的转换器,而不是默认的gson的

到此这篇关于聊聊springboot中如何自定义消息转换器的文章就介绍到这了,更多相关springboot 消息转换器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • idea compile项目正常启动项目的时候build失败报“找不到符号”等问题及解决方案

    idea compile项目正常启动项目的时候build失败报“找不到符号”等问题及解决方案

    这篇文章主要介绍了idea compile项目正常,启动项目的时候build失败,报“找不到符号”等问题,这种问题属于lombok编译失败导致,可能原因是依赖jar包没有更新到最新版本,需要的朋友可以参考下
    2023-10-10
  • Spring @Valid和@Validated区别和用法实例

    Spring @Valid和@Validated区别和用法实例

    这篇文章主要介绍了Spring @Valid和@Validated区别和用法实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • java中如何实现对类的对象进行排序

    java中如何实现对类的对象进行排序

    在本篇文章里小编给各位整理一篇关于java中如何实现对类的对象进行排序知识点内容,有兴趣的朋友们可以学习下。
    2020-02-02
  • idea中加入git版本控制的方法及步骤详解

    idea中加入git版本控制的方法及步骤详解

    在idea中加入git版本控制,方便团队中多人协同开发,项目可以同时方便进行管理和迭代。下面就是idea中加入git 的方法和步骤,感兴趣的朋友一起看看吧
    2021-09-09
  • spring @profile注解的使用方法

    spring @profile注解的使用方法

    本篇文章主要介绍了spring @profile注解的使用方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • SpringBoot和前端Vue的跨域问题及解决方案

    SpringBoot和前端Vue的跨域问题及解决方案

    所谓跨域就是从 A 向 B 发请求,如若他们的地址协议、域名、端口都不相同,直接访问就会造成跨域问题,跨域是非常常见的现象,这篇文章主要介绍了解决SpringBoot和前端Vue的跨域问题,需要的朋友可以参考下
    2023-11-11
  • 在Java中实现线程之间的数据共享的几种方式总结

    在Java中实现线程之间的数据共享的几种方式总结

    在 Java 中实现线程间数据共享是并发编程的核心需求,但需要谨慎处理同步问题以避免竞态条件,本文通过代码示例给大家介绍了几种主要实现方式及其最佳实践,需要的朋友可以参考下
    2025-08-08
  • Mybatis之RowBounds分页原理详解

    Mybatis之RowBounds分页原理详解

    这篇文章主要介绍了Mybatis之RowBounds分页原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-02-02
  • 聊聊注解@controller@service@component@repository的区别

    聊聊注解@controller@service@component@repository的区别

    这篇文章主要介绍了聊聊注解@controller@service@component@repository的区别,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08
  • IDEA之翻译器的使用Translation

    IDEA之翻译器的使用Translation

    这篇文章主要介绍了IDEA之翻译器的使用Translation,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05

最新评论