当前位置: 首页 > news >正文

spring-boot2.x,使用EnableWebMvc注解导致的自定义HttpMessageConverters不可用

在json对象转换方面,springboot默认使用的是MappingJackson2HttpMessageConverter。常规需求,在工程中使用阿里的FastJson作为json对象的转换器。

FastJson SerializerFeatures

WriteNullListAsEmpty  :List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty : 字符类型字段如果为null,输出为"",而非null
DisableCircularReferenceDetect :消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null
WriteMapNullValue:是否输出值为null的字段,默认为false。

public enum SerializerFeature {QuoteFieldNames,UseSingleQuotes,WriteMapNullValue,WriteEnumUsingToString,WriteEnumUsingName,UseISO8601DateFormat,WriteNullListAsEmpty,WriteNullStringAsEmpty,WriteNullNumberAsZero,WriteNullBooleanAsFalse,SkipTransientField,SortField,/** @deprecated */@DeprecatedWriteTabAsSpecial,PrettyFormat,WriteClassName,DisableCircularReferenceDetect,WriteSlashAsSpecial,BrowserCompatible,WriteDateUseDateFormat,NotWriteRootClassName,/** @deprecated */DisableCheckSpecialChar,BeanToArray,WriteNonStringKeyAsString,NotWriteDefaultValue,BrowserSecure,IgnoreNonFieldGetter,WriteNonStringValueAsString,IgnoreErrorGetter,WriteBigDecimalAsPlain,MapSortField;
}

使用FastJson,有两种常规操作。

一、注入bean的方式,这种方法加入的转换器排序是第一位

package com.gaoshan.verification.config;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 WebMvcConfigurerConfig implements WebMvcConfigurer {@Overridepublic void extendMessageConverters(List<HttpMessageConverter<?>> converters) {for (HttpMessageConverter<?> messageConverter : converters) {System.out.println("======================"+messageConverter);}}
}
package com.gaoshan.verification.config;import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;import java.util.ArrayList;
import java.util.List;@Configuration
public class MessageConvertConfig {@Beanpublic HttpMessageConverters fastJsonHttpMessageConverters() {FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();FastJsonConfig fastJsonConfig = new FastJsonConfig();fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteBigDecimalAsPlain,SerializerFeature.WriteMapNullValue);fastConverter.setFastJsonConfig(fastJsonConfig);List<MediaType> supportedMediaTypes = new ArrayList<>();supportedMediaTypes.add(MediaType.APPLICATION_JSON);fastConverter.setSupportedMediaTypes(supportedMediaTypes);return new HttpMessageConverters(fastConverter);}
}

======================com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter@2c5708e7
======================org.springframework.http.converter.ByteArrayHttpMessageConverter@4ffa078d
======================org.springframework.http.converter.StringHttpMessageConverter@4e26564d
======================org.springframework.http.converter.ResourceHttpMessageConverter@42238078
======================org.springframework.http.converter.ResourceRegionHttpMessageConverter@5627b8eb
======================org.springframework.http.converter.xml.SourceHttpMessageConverter@49fe0bcd
======================org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter@3516b881
======================org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@6be8ce1b
======================org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@e3c36d

二、实现WebMvcConfigurer接口,这种方法加入的转换器排序是最后一位

package com.gaoshan.verification.config;import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.util.ArrayList;
import java.util.List;@Configuration
public class WebMvcConfigurerConfig implements WebMvcConfigurer {@Overridepublic void extendMessageConverters(List<HttpMessageConverter<?>> converters) {for (HttpMessageConverter<?> messageConverter : converters) {System.out.println("======================"+messageConverter);}}@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();FastJsonConfig fastJsonConfig = new FastJsonConfig();fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteBigDecimalAsPlain,SerializerFeature.WriteMapNullValue);fastConverter.setFastJsonConfig(fastJsonConfig);List<MediaType> supportedMediaTypes = new ArrayList<>();supportedMediaTypes.add(MediaType.APPLICATION_JSON);fastConverter.setSupportedMediaTypes(supportedMediaTypes);converters.add(fastConverter);}
}

 ======================org.springframework.http.converter.ByteArrayHttpMessageConverter@71f29d91
======================org.springframework.http.converter.StringHttpMessageConverter@6785df10
======================org.springframework.http.converter.StringHttpMessageConverter@6143b2b1
======================org.springframework.http.converter.ResourceHttpMessageConverter@a63643e
======================org.springframework.http.converter.ResourceRegionHttpMessageConverter@43294e9b
======================org.springframework.http.converter.xml.SourceHttpMessageConverter@26d24d7a
======================org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter@5a78b52b
======================org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@144440f5
======================org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@4bab78ce
======================org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@42ffbab6
======================com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter@7672960e

注意:

1、可以两种方式同时使用,这样可以达到目的,在转换器列表的头尾,都会出现FastJsonHttpMessageConverter

======================com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter@2c5708e7
======================org.springframework.http.converter.ByteArrayHttpMessageConverter@4ffa078d
======================org.springframework.http.converter.StringHttpMessageConverter@4e26564d
======================org.springframework.http.converter.ResourceHttpMessageConverter@42238078
======================org.springframework.http.converter.ResourceRegionHttpMessageConverter@5627b8eb
======================org.springframework.http.converter.xml.SourceHttpMessageConverter@49fe0bcd
======================org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter@3516b881
======================org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@6be8ce1b
======================org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@e3c36d
======================com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter@397a10df

 

2、不要乱加 @EnableWebMvc标签,这个标签会导致添加自定义消息转换器失败。因为时间问题,目前还不清楚具体原因

  • 针对方案一,启动类或任意配置类,加了@EnableWebMvc后,导致自定义的转换器没有出现在集合内,即添加自定义转换器失败
package com.gaoshan.verification.config;import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.util.List;@Configuration
@EnableWebMvc
public class WebMvcConfigurerConfig implements WebMvcConfigurer {@Overridepublic void extendMessageConverters(List<HttpMessageConverter<?>> converters) {for (HttpMessageConverter<?> messageConverter : converters) {System.out.println("======================"+messageConverter);}}
}
package com.gaoshan.verification.config;import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;import java.util.ArrayList;
import java.util.List;@Configuration
public class MessageConvertConfig {@Beanpublic HttpMessageConverters fastJsonHttpMessageConverters() {FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();FastJsonConfig fastJsonConfig = new FastJsonConfig();fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteBigDecimalAsPlain,SerializerFeature.WriteMapNullValue);fastConverter.setFastJsonConfig(fastJsonConfig);List<MediaType> supportedMediaTypes = new ArrayList<>();supportedMediaTypes.add(MediaType.APPLICATION_JSON);fastConverter.setSupportedMediaTypes(supportedMediaTypes);return new HttpMessageConverters(fastConverter);}
}

 ======================org.springframework.http.converter.ByteArrayHttpMessageConverter@42238078
======================org.springframework.http.converter.StringHttpMessageConverter@5627b8eb
======================org.springframework.http.converter.ResourceHttpMessageConverter@49fe0bcd
======================org.springframework.http.converter.ResourceRegionHttpMessageConverter@3516b881
======================org.springframework.http.converter.xml.SourceHttpMessageConverter@6be8ce1b
======================org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter@e3c36d
======================org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@397a10df
======================org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@39a865c1

  • 针对方案二,启动类或任意配置类,加了@EnableWebMvc后,导致集合内仅有自定义转换器
package com.gaoshan.verification.config;import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.util.ArrayList;
import java.util.List;@Configuration
@EnableWebMvc
public class WebMvcConfigurerConfig implements WebMvcConfigurer {@Overridepublic void extendMessageConverters(List<HttpMessageConverter<?>> converters) {for (HttpMessageConverter<?> messageConverter : converters) {System.out.println("======================"+messageConverter);}}@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();FastJsonConfig fastJsonConfig = new FastJsonConfig();fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteBigDecimalAsPlain,SerializerFeature.WriteMapNullValue);fastConverter.setFastJsonConfig(fastJsonConfig);List<MediaType> supportedMediaTypes = new ArrayList<>();supportedMediaTypes.add(MediaType.APPLICATION_JSON);fastConverter.setSupportedMediaTypes(supportedMediaTypes);converters.add(fastConverter);}
}

======================com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter@1df06ecd

  • 启动类代码
    package com;import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
    public class VerificationApplication {public static void main(String[] args) {SpringApplication.run(VerificationApplication.class, args);}}
    
     
http://www.lryc.cn/news/171431.html

相关文章:

  • 2023-09-20 Android CheckBox 让文字显示在选择框的左边
  • 目标检测YOLO实战应用案例100讲-基于改进YOLOv5的口罩人脸检测
  • CentOS7 yum安装报错:“Could not resolve host: mirrorlist.centos.org; Unknown error“
  • 关于token续签
  • 淘宝分布式文件存储系统( 二 ) -TFS
  • Java中synchronized:特性、使用、锁机制与策略简析
  • 记一次clickhouse手动更改分片数异常
  • 深度学习论文: ISTDU-Net:Infrared Small-Target Detection U-Net及其PyTorch实现
  • 图像识别-YOLO V8安装部署-window-CPU-Pycharm
  • js禁用F1至F12、禁止缩放、取消选中并且取消右键操作、打印、拖拽、鼠标点击弹出自定义信息、禁用开发者工具js
  • Zabbix5.0_介绍_组成架构_以及和prometheus的对比_大数据环境下的监控_网络_软件_设备监控_Zabbix工作笔记
  • 百度SEO优化TDK介绍(分析下降原因并总结百度优化SEO策略)
  • 搭建自动化 Web 页面性能检测系统 —— 设计篇
  • 记一次 mysql 数据库定时备份
  • 淘宝分布式文件存储系统(一) -TFS
  • LLM各层参数详细分析(以LLaMA为例)
  • linux ansible(三)
  • Anaconda和Pycharm详细安装 配置教程
  • 利用Linux虚拟化技术实现资源隔离和管理
  • 12基于MATLAB的短时傅里叶变换( STFT),连续小波变换( CWT),程序已调通,可以直接运行。
  • k8s使用时无法ping通服务器From IP地址 icmp_seq=1 Destination Host Unreachable
  • 两种风格的纯CSS3加载动画
  • Spring Cloud Eureka:服务注册与发现
  • 安防监控视频云存储平台EasyNVR对接EasyNVS时,一直不上线该如何解决?
  • 【完美解决】GitHub连接超时问题 Recv failure: Connection was reset
  • cpolar内网穿透
  • go语言操作数据库
  • zabbix实现钉钉报警
  • 基于微信小程序的语言课学习系统设计与实现(源码+lw+部署文档+讲解等)
  • R 语言画图中英文字体解决方案