SpringBoot添加自定義消息轉(zhuǎn)換器

本文章僅供小編學(xué)習(xí)使用,如有侵犯他人版權(quán),請聯(lián)系小編撤回或刪除

首先我們需要明白一個概念:

springboot中很多配置都是使用了條件注解進(jìn)行判斷一個配置或者引入的類是否在容器中存在,如果存在會如何,如果不存在會如何。

也就是說,有些配置會在springboot中有默認(rèn)配置,前提是你沒有配置,這樣來起到簡化配置作用。如果你配置了,容器就不會為你再去默認(rèn)配置。

配置消息轉(zhuǎn)化器的兩種方法:

方法一:自定義消息轉(zhuǎn)化器,只需要在@Configuration的類中添加消息轉(zhuǎn)化器的@bean加入到Spring容器,就會被Spring Boot自動加入到容器中。

/**
 * @program: workspace
 * @description: 自定義消息轉(zhuǎn)換器
 * @author: 劉宗強(qiáng)
 * @create: 2019-08-28 15:32
 **/

@Configuration
public class WebMvcConfigurerAdapter {
    /**
     * 自定義字符串轉(zhuǎn)換器
     * @return
     */
    @Bean
    public StringHttpMessageConverter stringHttpMessageConverter(){
        StringHttpMessageConverter converter  = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        return converter;
    }

    /**
     * 自定義fastJson轉(zhuǎn)換器
     * @return
     */
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters(){
        //1.需要定義一個convert轉(zhuǎn)換消息的對象;
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        //2:添加fastJson的配置信息;
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //3處理中文亂碼問題
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        //4.在convert中添加配置信息.
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
        return new HttpMessageConverters(converter);

    }
}

方法二:請查看文章底部原文

原文地址:https://www.cnblogs.com/hellxz/p/8735602.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容