最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

聊聊springboot中如何自定義消息轉(zhuǎn)換器

 更新時(shí)間:2025年08月15日 12:15:59   作者:白衣神棍  
SpringBoot通過HttpMessageConverter處理HTTP數(shù)據(jù)轉(zhuǎn)換,支持多種媒體類型,接下來通過本文給大家介紹springboot中如何自定義消息轉(zhuǎn)換器,感興趣的朋友一起看看吧

Spring Boot 中的消息轉(zhuǎn)換器(HttpMessageConverter)是處理 HTTP 請求和響應(yīng)數(shù)據(jù)格式轉(zhuǎn)換的核心組件,負(fù)責(zé)將 HTTP 請求體中的數(shù)據(jù)轉(zhuǎn)換為 Java 對象,或?qū)?Java 對象轉(zhuǎn)換為 HTTP 響應(yīng)體的數(shù)據(jù)。

核心接口

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:執(zhí)行具體的數(shù)據(jù)轉(zhuǎn)換邏輯

springboot默認(rèn)提供的轉(zhuǎn)換器

Spring Boot 自動(dòng)配置了以下常用消息轉(zhuǎn)換器:

  1. StringHttpMessageConverter - 處理文本數(shù)據(jù)
  2. MappingJackson2HttpMessageConverter - 處理 JSON 數(shù)據(jù)(使用 Jackson)
  3. FormHttpMessageConverter - 處理表單數(shù)據(jù)
  4. ByteArrayHttpMessageConverter - 處理字節(jié)數(shù)組
  5. ResourceHttpMessageConverter - 處理資源文件
  6. Jaxb2RootElementHttpMessageConverter - 處理 XML(使用 JAXB)
  7. AllEncompassingFormHttpMessageConverter - 增強(qiáng)的表單處理器

springboot在啟動(dòng)的時(shí)候就會自動(dòng)注冊上述默認(rèn)的轉(zhuǎn)換器,有請求進(jìn)來的時(shí)候會根據(jù)請求的accept和響應(yīng)的Content-Type,選擇匹配的轉(zhuǎn)換器,若多個(gè)轉(zhuǎn)換器都支持,則按注冊順序優(yōu)先。

如何自定義消息轉(zhuǎn)換器

比如自定義個(gè)fastjson轉(zhuǎn)換器

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());
    }
}

注冊自定義的消息轉(zhuǎn)換器 

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) {
        // 創(chuàng)建FastJson消息轉(zhuǎn)換器
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        // 可以在這里進(jìn)一步配置FastJson
        // fastJsonConverter.getFastJsonConfig().setDateFormat("yyyy-MM-dd");
        // 將FastJson轉(zhuǎn)換器添加到轉(zhuǎn)換器列表的最前面
        converters.add(0, fastJsonConverter);
    }
}

注意這里優(yōu)先級的問題,要把fastjson的放前面,這樣才會優(yōu)先走咱自定義的fastjson的轉(zhuǎn)換器,而不是默認(rèn)的gson的

到此這篇關(guān)于聊聊springboot中如何自定義消息轉(zhuǎn)換器的文章就介紹到這了,更多相關(guān)springboot 消息轉(zhuǎn)換器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot使用swagger生成api接口文檔的方法詳解

    SpringBoot使用swagger生成api接口文檔的方法詳解

    在之前的文章中,使用mybatis-plus生成了對應(yīng)的包,在此基礎(chǔ)上,我們針對項(xiàng)目的api接口,添加swagger配置和注解,生成swagger接口文檔,需要的可以了解一下
    2022-10-10
  • SpringMVC 接收前端傳遞的參數(shù)四種方式小結(jié)

    SpringMVC 接收前端傳遞的參數(shù)四種方式小結(jié)

    這篇文章主要介紹了SpringMVC 接收前端傳遞的參數(shù)四種方式小結(jié),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Spring的事件和監(jiān)聽器-同步與異步詳解

    Spring的事件和監(jiān)聽器-同步與異步詳解

    這篇文章主要介紹了Spring的事件和監(jiān)聽器-同步與異步詳解,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • SpringBoot加載profile全面解析

    SpringBoot加載profile全面解析

    SpringBoot的Profile機(jī)制通過多配置文件和注解實(shí)現(xiàn)環(huán)境隔離,支持開發(fā)、測試、生產(chǎn)等不同環(huán)境的靈活配置切換,無需修改代碼,關(guān)鍵點(diǎn)包括配置文件命名規(guī)范、激活方式、優(yōu)先級及企業(yè)級安全部署實(shí)踐,本文介紹SpringBoot加載profile的過程,感興趣的朋友一起看看吧
    2025-08-08
  • Java多線程中wait、notify、notifyAll使用詳解

    Java多線程中wait、notify、notifyAll使用詳解

    這篇文章主要介紹了Java多線程中wait、notify、notifyAll使用詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-05-05
  • Java鎖擦除與鎖粗化概念和使用詳解

    Java鎖擦除與鎖粗化概念和使用詳解

    這篇文章主要介紹了Java鎖擦除與鎖粗化概念和使用,鎖擦除的主要判定依據(jù)來源于逃逸分析的數(shù)據(jù)支持,如果判斷在一段代碼中,堆上的所有數(shù)據(jù)都不會逃逸出去從而被其他線程訪問到,那就可以把它們當(dāng)做棧上數(shù)據(jù)對待,認(rèn)為它們是線程私有的,同步加鎖自然就無須進(jìn)行
    2023-02-02
  • 淺析JPA分類表的操作函數(shù)

    淺析JPA分類表的操作函數(shù)

    這篇文章主要介紹了JPA分類表的操作函數(shù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧
    2023-02-02
  • Java訪問控制符原理及具體用法解析

    Java訪問控制符原理及具體用法解析

    這篇文章主要介紹了Java訪問控制符原理及具體用法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11
  • SpringBoot整合RabbitMQ實(shí)現(xiàn)流量消峰

    SpringBoot整合RabbitMQ實(shí)現(xiàn)流量消峰

    RabbitMQ 即一個(gè)消息隊(duì)列,主要是用來實(shí)現(xiàn)應(yīng)用程序的異步和解耦,同時(shí)也能起到消息緩沖,消息分發(fā)的作用,消息中間件在互聯(lián)網(wǎng)公司的使用中越來越多,本文給大家介紹了SpringBoot整合RabbitMQ實(shí)現(xiàn)流量消峰,需要的朋友可以參考下
    2024-12-12
  • springboot CompletableFuture并行計(jì)算及使用方法

    springboot CompletableFuture并行計(jì)算及使用方法

    CompletableFuture基于 Future 和 CompletionStage 接口,利用線程池、回調(diào)函數(shù)、異常處理、組合操作等機(jī)制,提供了強(qiáng)大而靈活的異步編程功能,這篇文章主要介紹了springboot CompletableFuture并行計(jì)算及使用方法,需要的朋友可以參考下
    2024-05-05

最新評論

白银市| 邛崃市| 牙克石市| 华安县| 阿勒泰市| 南充市| 云阳县| 凤山县| 石林| 乐安县| 康定县| 吉木萨尔县| 广西| 桦甸市| 吉林省| 镇康县| 马关县| 南安市| 上饶市| 任丘市| 巢湖市| 新密市| 嘉定区| 娱乐| 涿州市| 香港 | 壤塘县| 龙里县| 卢氏县| 军事| 英山县| 新巴尔虎左旗| 金溪县| 简阳市| 榆树市| 永新县| 开远市| 洛浦县| 阳城县| 黔西| 长治县|