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.mzph.cn/news/83660.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

云原生的简单理解

一、何谓云原生&#xff1f; 一种构建和运行应用软件的方法 应用程序从设计之初即考虑到云的环境&#xff0c;原生为云而设计&#xff0c;在云上以最佳姿势运行&#xff0c;充分利用和发挥云平台的弹性分布式优势。 二、包括以下四个要素 采用容器化部署&#xff1a;实现云平…

MySQL学习系列(4)-每天学习10个知识

目录 1. InnoDB 和 MyISAM2. SQL调优3. 数据一致性问题的解决4. MySQL的存储引擎5. MySQL的内存使用问题6. 索引比全表扫描慢的情况7. 行级锁和表级锁8. MySQL的复制功能9. 数据库性能测试10. 数据库管理和优化 &#x1f44d; 点赞&#xff0c;你的认可是我创作的动力&#xff…

SQL Server 入门知识

&#x1f648;作者简介&#xff1a;练习时长两年半的Java up主 &#x1f649;个人主页&#xff1a;程序员老茶 &#x1f64a; ps:点赞&#x1f44d;是免费的&#xff0c;却可以让写博客的作者开兴好久好久&#x1f60e; &#x1f4da;系列专栏&#xff1a;Java全栈&#xff0c;…

el-table表格中加入输入框

<template><div class"box"><div class"btn"><el-button type"primary">发送评委</el-button><el-button type"primary" click"flag true" v-if"!flag">编辑</el-button…

面试系列之《LinuxShell》(更新中)

1.用awk命令实现一个词频统计。 假设文件名“data”&#xff0c;文件内容&#xff1a; A B C D A C D D B C C 1.1. python实现 因为不熟悉awk命令&#xff0c;当时用python实现的&#xff1a; res_dict {} with open(./data, r, encodingutf-8) as fp:for line in fp:for …

win系统环境搭建(九)——Windows安装chatGPT

windows环境搭建专栏&#x1f517;点击跳转 win系统环境搭建&#xff08;九&#xff09;——Windows安装chatGPT 本系列windows环境搭建开始讲解如何给win系统搭建环境&#xff0c;本人所用系统是腾讯云服务器的Windows Server 2022&#xff0c;你可以理解成就是你用的windows…

使用 nohup 运行 Python 脚本

简介&#xff1a;在数据科学、Web 开发或者其他需要长时间运行的任务中&#xff0c;我们经常需要让 Python 脚本在后台运行。尤其是在远程服务器上&#xff0c;可能因为网络不稳定或需要执行多个任务&#xff0c;我们不希望 Python 脚本因为终端关闭而被终止。这时&#xff0c;…

全球南方《乡村振兴战略下传统村落文化旅游设计》许少辉八一著辉少许

全球南方《乡村振兴战略下传统村落文化旅游设计》许少辉八一著辉少许

达梦数据库随系统开机自动启动脚本

写一个脚本&#xff0c;实现在服务器开机后自动启动达梦数据库的功能。 1. 在/etc/init.d/目录下&#xff0c;编写脚本&#xff0c;并将脚本命名为startdm.sh。脚本内容实现如下&#xff1a; #!/bin/bash #chkconfig:2345 80 90 #decription:启动达梦# 切换到 dmdba 用户 su …

Unity云原生分布式运行时

// 元宇宙时代的来临对实时3D引擎提出了诸多要求&#xff0c;Unity作为游戏行业应用最广泛的3D实时内容创作引擎&#xff0c;为应对这些新挑战&#xff0c;提出了Unity云原生分布式运行时的解决方案。LiveVideoStack 2023上海站邀请到Unity中国的解决方案工程师舒润萱&#x…

倒计时列表实现(小程序端Vue)

//rich-text主要用来将展示html格式的&#xff0c;可以直接使用这个标签 <view class"ptBox" v-for"(item,index) in orderList" :key"index"> <rich-text :nodes"item.limit_time|limitTimeFilter"></rich-text>…

2023_Spark_实验十二:Spark高级算子使用

掌握Spark高级算子在代码中的使用 相同点分析 三个函数的共同点&#xff0c;都是Transformation算子。惰性的算子。 不同点分析 map函数是一条数据一条数据的处理&#xff0c;也就是&#xff0c;map的输入参数中要包含一条数据以及其他你需要传的参数。 mapPartitions函数是一个…

网络编程day03(UDP中的connect函数、tftp)

今日任务&#xff1a;tftp的文件上传下载&#xff08;服务端已经准备好&#xff09; 服务端&#xff08;已上传&#xff09; 客户端&#xff1a; 代码&#xff1a; #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/types.h…

编译工具:CMake(八) | cmake 常用指令

编译工具&#xff1a;CMake&#xff08;八&#xff09; | cmake 常用指令 基本指令 基本指令 ADD_DEFINITIONS向 C/C编译器添加-D 定义&#xff0c;比如:ADD_DEFINITIONS(-DENABLE_DEBUG-DABC)&#xff0c;参数之间用空格分割。 如果你的代码中定义了#ifdef ENABLE_DEBUG #end…

Java 调用 GitLabAPI 获取仓库里的文件件 提交记录

1. 需求 项目组 需要做统计&#xff0c;获取每个开发人员的代码提交次数&#xff0c;提交时间&#xff0c;提交人等等&#xff0c;因代码在GitLab上管理&#xff0c;所以需要调用GitLabAPI来获取。 2. 开发 API官网&#xff1a;https://docs.gitlab.com/ee/api/ 2.1 创建自…

java Spring Boot验证码美化,白色背景 随机四个数 每个字随机颜色

我前文 Spring Boot2.7生成用于登录的图片验证码讲述了生成验证码的方法 但是这样生成验证码 非常难看 比较说 验证码是要展示到web程序中的 这样让用户看着 属实不太好 我们可以将接口改成 GetMapping(value "/captcha", produces MediaType.IMAGE_PNG_VALUE) …

Spring Task(简略笔记)

介绍 Spring Task是Spring框架提供的任务调度工具&#xff0c;可以按照约定的时间自动执行某个代码逻辑。 Corn表达式 corn表达式其实就是一个字符串&#xff0c;通过corn表达式可以定有任务触发的时间 构成规则&#xff1a;分为6或7个域&#xff0c;由空格分隔开&#xff0…

RocketMQ 发送事务消息

文章目录 事务的相关理论事务ACID特性CAP 理论BASE 理论 事务消息应用场景MQ 事务消息处理处理逻辑 RocketMQ 事务消息处理流程官网事务消息流程图 rocketmq-client-java 示例&#xff08;gRPC 协议&#xff09;创建事务主题生产者消费者 rocketmq-client 示例&#xff08;Remo…

代码随想录Day1 数组基础

本文详细说明和思路来源于: 代码随想录 视频讲解: 手把手带你撕出正确的二分法 | 二分查找法 | 二分搜索法 | LeetCode&#xff1a;704. 二分查找_哔哩哔哩_bilibili Leetcode T 704 题目链接 704. 二分查找 - 力扣&#xff08;LeetCode&#xff09; 题目概述1: 思路: 1.因…

基于微信小程序的高校宿舍信息管理系统设计与实现(源码+lw+部署文档+讲解等)

前言 &#x1f497;博主介绍&#xff1a;✌全网粉丝10W,CSDN特邀作者、博客专家、CSDN新星计划导师、全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战✌&#x1f497; &#x1f447;&#x1f3fb;…