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

2025-08-15 21:50

本文主要是介绍聊聊springboot中如何自定义消息转换器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《聊聊springboot中如何自定义消息转换器》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
 js           );
        }
    }
    @Override
    protected void writeInternal(
            @NonNull Object object,
            @NonNull HttpOutputMessage outputMessage
    ) throws IOExceptwww.chinasem.cnion, 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 getFastJsonCowww.chinasem.cnnfig() {
        return fastJsonConfig;
    }
    public void setFastJsonConfig(FastJsonConfig fastJsonConfig) {
        this.fastJsonConfig.setDateFormat(fastJsonConfig.getDateFormat());
        this.fastJsonConfig.setCharset(fastJsonCHKakCnonfig.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 消息转换器内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于聊聊springboot中如何自定义消息转换器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1155758

相关文章

Springboot项目构建时各种依赖详细介绍与依赖关系说明详解

《Springboot项目构建时各种依赖详细介绍与依赖关系说明详解》SpringBoot通过spring-boot-dependencies统一依赖版本管理,spring-boot-starter-w... 目录一、spring-boot-dependencies1.简介2. 内容概览3.核心内容结构4.

Spring Boot 整合 SSE(Server-Sent Events)实战案例(全网最全)

《SpringBoot整合SSE(Server-SentEvents)实战案例(全网最全)》本文通过实战案例讲解SpringBoot整合SSE技术,涵盖实现原理、代码配置、异常处理及前端交互,... 目录Spring Boot 整合 SSE(Server-Sent Events)1、简述SSE与其他技术的对

Spring Security 前后端分离场景下的会话并发管理

《SpringSecurity前后端分离场景下的会话并发管理》本文介绍了在前后端分离架构下实现SpringSecurity会话并发管理的问题,传统Web开发中只需简单配置sessionManage... 目录背景分析传统 web 开发中的 sessionManagement 入口ConcurrentSess

Java整合Protocol Buffers实现高效数据序列化实践

《Java整合ProtocolBuffers实现高效数据序列化实践》ProtocolBuffers是Google开发的一种语言中立、平台中立、可扩展的结构化数据序列化机制,类似于XML但更小、更快... 目录一、Protocol Buffers简介1.1 什么是Protocol Buffers1.2 Pro

Java实现本地缓存的四种方法实现与对比

《Java实现本地缓存的四种方法实现与对比》本地缓存的优点就是速度非常快,没有网络消耗,本地缓存比如caffine,guavacache这些都是比较常用的,下面我们来看看这四种缓存的具体实现吧... 目录1、HashMap2、Guava Cache3、Caffeine4、Encache本地缓存比如 caff

MyBatis-Plus 与 Spring Boot 集成原理实战示例

《MyBatis-Plus与SpringBoot集成原理实战示例》MyBatis-Plus通过自动配置与核心组件集成SpringBoot实现零配置,提供分页、逻辑删除等插件化功能,增强MyBa... 目录 一、MyBATis-Plus 简介 二、集成方式(Spring Boot)1. 引入依赖 三、核心机制

Java高效实现Word转PDF的完整指南

《Java高效实现Word转PDF的完整指南》这篇文章主要为大家详细介绍了如何用Spire.DocforJava库实现Word到PDF文档的快速转换,并解析其转换选项的灵活配置技巧,希望对大家有所帮助... 目录方法一:三步实现核心功能方法二:高级选项配置性能优化建议方法补充ASPose 实现方案Libre

springboot整合mqtt的步骤示例详解

《springboot整合mqtt的步骤示例详解》MQTT(MessageQueuingTelemetryTransport)是一种轻量级的消息传输协议,适用于物联网设备之间的通信,本文介绍Sprin... 目录1、引入依赖包2、yml配置3、创建配置4、自定义注解6、使用示例使用场景:mqtt可用于消息发

Java List 使用举例(从入门到精通)

《JavaList使用举例(从入门到精通)》本文系统讲解JavaList,涵盖基础概念、核心特性、常用实现(如ArrayList、LinkedList)及性能对比,介绍创建、操作、遍历方法,结合实... 目录一、List 基础概念1.1 什么是 List?1.2 List 的核心特性1.3 List 家族成

Java 中编码与解码的具体实现方法

《Java中编码与解码的具体实现方法》在Java中,字符编码与解码是处理数据的重要组成部分,正确的编码和解码可以确保字符数据在存储、传输、读取时不会出现乱码,本文将详细介绍Java中字符编码与解码的... 目录Java 中编码与解码的实现详解1. 什么是字符编码与解码?1.1 字符编码(Encoding)1