聊聊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

相关文章

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

Java中的.close()举例详解

《Java中的.close()举例详解》.close()方法只适用于通过window.open()打开的弹出窗口,对于浏览器的主窗口,如果没有得到用户允许是不能关闭的,:本文主要介绍Java中的.... 目录当你遇到以下三种情况时,一定要记得使用 .close():用法作用举例如何判断代码中的 input

Spring Gateway动态路由实现方案

《SpringGateway动态路由实现方案》本文主要介绍了SpringGateway动态路由实现方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随... 目录前沿何为路由RouteDefinitionRouteLocator工作流程动态路由实现尾巴前沿S

JavaScript对象转数组的三种方法实现

《JavaScript对象转数组的三种方法实现》本文介绍了在JavaScript中将对象转换为数组的三种实用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友... 目录方法1:使用Object.keys()和Array.map()方法2:使用Object.entr

idea+spring boot创建项目的搭建全过程

《idea+springboot创建项目的搭建全过程》SpringBoot是Spring社区发布的一个开源项目,旨在帮助开发者快速并且更简单的构建项目,:本文主要介绍idea+springb... 目录一.idea四种搭建方式1.Javaidea命名规范2JavaWebTomcat的安装一.明确tomcat

Java高效实现PowerPoint转PDF的示例详解

《Java高效实现PowerPoint转PDF的示例详解》在日常开发或办公场景中,经常需要将PowerPoint演示文稿(PPT/PPTX)转换为PDF,本文将介绍从基础转换到高级设置的多种用法,大家... 目录为什么要将 PowerPoint 转换为 PDF安装 Spire.Presentation fo