美文网首页
SpringBoot添加自定义消息转换器

SpringBoot添加自定义消息转换器

作者: 花劫_8b1c | 来源:发表于2019-08-28 16:04 被阅读0次

    本文章仅供小编学习使用,如有侵犯他人版权,请联系小编撤回或删除

    首先我们需要明白一个概念:

    springboot中很多配置都是使用了条件注解进行判断一个配置或者引入的类是否在容器中存在,如果存在会如何,如果不存在会如何。

    也就是说,有些配置会在springboot中有默认配置,前提是你没有配置,这样来起到简化配置作用。如果你配置了,容器就不会为你再去默认配置。

    配置消息转化器的两种方法:

    方法一:自定义消息转化器,只需要在@Configuration的类中添加消息转化器的@bean加入到Spring容器,就会被Spring Boot自动加入到容器中。

    /**
     * @program: workspace
     * @description: 自定义消息转换器
     * @author: 刘宗强
     * @create: 2019-08-28 15:32
     **/
    
    @Configuration
    public class WebMvcConfigurerAdapter {
        /**
         * 自定义字符串转换器
         * @return
         */
        @Bean
        public StringHttpMessageConverter stringHttpMessageConverter(){
            StringHttpMessageConverter converter  = new StringHttpMessageConverter(Charset.forName("UTF-8"));
            return converter;
        }
    
        /**
         * 自定义fastJson转换器
         * @return
         */
        @Bean
        public HttpMessageConverters fastJsonHttpMessageConverters(){
            //1.需要定义一个convert转换消息的对象;
            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

    相关文章

      网友评论

          本文标题:SpringBoot添加自定义消息转换器

          本文链接:https://www.haomeiwen.com/subject/mqqmectx.html