springboot升级2.0+ 整合fastjson

SpringBoot2.0如何集成fastjson?在网上查了一堆资料,但是各文章的说法不一,有些还是错的,可能只是简单测试一下就认为ok了,最后有没生效都不知道。恰逢公司项目需要将JackSon换成fastjson,因此自己来实践一下SpringBoot2.0和fastjson的整合,同时记录下来方便自己后续查阅。

一、Maven依赖说明

  SpringBoot的版本为: <version>2.1.4.RELEASE</version>

  在pom文件中添加fastjson的依赖:

<dependency>
         <groupId>com.alibaba</groupId>
         <artifactId>fastjson</artifactId>
         <version>1.2.60/version>
</dependency>

二、整合

  整合之前,我们先说下springboot1.0的方法,轻车熟路的去自定了一个SpringMvcConfigure去继承WebMvcConfigurerAdapter,然后你就发现这个WebMvcConfigurerAdapter竟然过时了?what?点进去看源码:

 1 /**
 2  * An implementation of {@link WebMvcConfigurer} with empty methods allowing
 3  * subclasses to override only the methods they‘re interested in.
 4  *
 5  * @author Rossen Stoyanchev
 6  * @since 3.1
 7  * @deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made
 8  * possible by a Java 8 baseline) and can be implemented directly without the
 9  * need for this adapter
10  */
11 @Deprecated
12 public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {}

  可以看到从spring5.0开始就被@Deprecated,原来是java8中支持接口中有默认方法,所以我们现在可以直接实现WebMvcConfigurer,然后选择性的去重写某个方法,而不用实现它的所有方法.

  于是就实现了WebMvcConfigurer:

 1 @Configuration
 2 public class SpringMvcConfigure implements WebMvcConfigurer {
 3
 4     /**
 5      * 配置消息转换器
 6      * @param converters
 7      */
 8     @Override
 9     public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
10         FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
11         //自定义配置...
12         FastJsonConfig config = new FastJsonConfig();
13         config.setSerializerFeatures(SerializerFeature.QuoteFieldNames,
14                 SerializerFeature.WriteEnumUsingToString,
15                 /*SerializerFeature.WriteMapNullValue,*/
16                 SerializerFeature.WriteDateUseDateFormat,
17                 SerializerFeature.DisableCircularReferenceDetect);
18         fastJsonHttpMessageConverter.setFastJsonConfig(config);
19         converters.add(fastJsonHttpMessageConverter);
20     }
21
22 }

  本以为这样子配置就可以完事儿,但是诡异的事情发生了,我明明注释了SerializerFeature.WriteMapNullValue,可是返回的json中仍然有为null的字段,然后我就去com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter中的writewriteInternal打了断点,再次执行,竟然什么都没有发生,根本没有走这两个方法,于是在自定义的SpringMvcConfigureconfigureMessageConverters方法内打了断点,想看看这个方法参数converters里边到底有什么:

  看到这里就想到,肯定是我自己添加的fastjson在后边,所以没有生效,所以就加了以下代码:

 1 @Override
 2 public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
 3     converters = converters.stream()
 4                 .filter((converter)-> !(converter instanceof MappingJackson2HttpMessageConverter))
 5                 .collect(Collectors.toList());
 6     FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
 7     //自定义配置...
 8     FastJsonConfig config = new FastJsonConfig();
 9     config.setSerializerFeatures(SerializerFeature.QuoteFieldNames,
10             SerializerFeature.WriteEnumUsingToString,
11             /*SerializerFeature.WriteMapNullValue,*/
12             SerializerFeature.WriteDateUseDateFormat,
13             SerializerFeature.DisableCircularReferenceDetect);
14     fastJsonHttpMessageConverter.setFastJsonConfig(config);
15     converters.add(fastJsonHttpMessageConverter);
16 }

  这还是不生效的,继续追踪,得出如下结论:

     (1)源码分析可知,返回json的过程为:           Controller调用结束后返回一个数据对象,for循环遍历conventers,找到支持application/json的HttpMessageConverter,然后将返回的数据序列化成json。           具体参考org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor的writeWithMessageConverters方法      (2)由于是list结构,我们添加的fastjson在最后。因此必须要将jackson的转换器删除,不然会先匹配上jackson,导致没使用fastjson

  最终得出代码如下:

 1 @Configuration
 2 public class SpringWebMvcConfigurer implements WebMvcConfigurer {
 3
 4     private final Logger logger = LoggerFactory.getLogger(SpringWebMvcConfigurer.class);
 5
 6     //使用阿里 FastJson 作为JSON MessageConverter
 7     @Override
 8     public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
 9
10          /*
11          先把JackSon的消息转换器删除.
12          备注: (1)源码分析可知,返回json的过程为:
13                     Controller调用结束后返回一个数据对象,for循环遍历conventers,找到支持application/json的HttpMessageConverter,然后将返回的数据序列化成json。
14                     具体参考org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor的writeWithMessageConverters方法
15                (2)由于是list结构,我们添加的fastjson在最后。因此必须要将jackson的转换器删除,不然会先匹配上jackson,导致没使用fastjson
16         */
17         for (int i = converters.size() - 1; i >= 0; i--) {
18             if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
19                 converters.remove(i);
20             }
21         }
22
23         FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
24         FastJsonConfig config = new FastJsonConfig();
25         config.setSerializerFeatures(
26                 SerializerFeature.WriteMapNullValue,//保留空的字段
27                 SerializerFeature.WriteNullStringAsEmpty,//String null -> ""
28                 SerializerFeature.WriteNullNumberAsZero,//Number null -> 0
29                 SerializerFeature.WriteDateUseDateFormat);//日期格式化
30
31         converter.setFastJsonConfig(config);
32         converter.setDefaultCharset(Charset.forName("UTF-8"));
33         converters.add(converter);
34     }
35 }

  总结

  1. 最重要的还是解决了springboot2.0.2配置fastjson不生效的问题
  2. 更加明白stream api返回的都是全新的对象
  3. 更理解java是值传递而不是引用传递
  4. 了解到想要在迭代过程中对集合进行操作要用Iterator,而不是直接简单的for循环或者增强for循环

原文地址:https://www.cnblogs.com/xujingyang/p/11679317.html

时间: 2024-07-31 00:16:38

springboot升级2.0+ 整合fastjson的相关文章

SpringBoot2.0整合fastjson的正确姿势

SpringBoot2.0如何集成fastjson?在网上查了一堆资料,但是各文章的说法不一,有些还是错的,可能只是简单测试一下就认为ok了,最后有没生效都不知道.恰逢公司项目需要将JackSon换成fastjson,因此自己来实践一下SpringBoot2.0和fastjson的整合,同时记录下来方便自己后续查阅. 一.Maven依赖说明 SpringBoot的版本为: <version>2.1.4.RELEASE</version> 在pom文件中添加fastjson的依赖:

springboot 升级到2.0后 context-path 配置 不起作用,不生效 不管用 皆是因为版本改动导致的在这里记录一下

不知不觉,新的项目已经将springboot升级为2.0版本了.刚开始没有配置server.contextpath,默认的"/",然后今天放到自己的服务器上,所以就要规范名称.  结果,失败了,无论我怎么配置,总是在启动后日志打印说 :path:"" 正确姿势:server.servlet.context-path:"/url" 版本更新东西还是不少,需要了解的还请移步spring官网自行查看版本信息 原文地址:https://www.cnblo

SpringBoot 2.0 整合shiro1.4 手记

---spring boot2.0 整合 shiro1.4 手记---------------- 1.---pom.xml添加依赖---------------------------------- <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> &

SpringBoot入门二十三,整合Redis

项目基本配置参考文章SpringBoot入门一,使用myEclipse新建一个SpringBoot项目,使用MyEclipse新建一个SpringBoot项目即可,此示例springboot升级为2.2.1版本. 1. pom.xml添加Redis支持 <!-- 5.引入redis依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-b

SpringBoot(二十六)整合Redis之共享Session

集群现在越来越常见,当我们项目搭建了集群,就会产生session共享问题.因为session是保存在服务器上面的.那么解决这一问题,大致有三个方案,1.通过nginx的负载均衡其中一种ip绑定来实现(通过ip绑定服务器其中一台,就没有集群概念了):2.通过cookie备份session实现(因为cookie数据保存在客户端,不推荐;3.通过redis备份session实现(推荐); 学习本章节之前,建议依次阅读以下文章,更好的串联全文内容,如已掌握以下列出知识点,请跳过: SpringBoot(

SpringBoot与PageHelper的整合示例详解

SpringBoot与PageHelper的整合示例详解 1.PageHelper简介 PageHelper官网地址: https://pagehelper.github.io/ 摘要: com.github.pagehelper.PageHelper是一款好用的开源免费的Mybatis第三方物理分页插件. PageHelper是一款好用的开源免费的Mybatis第三方物理分页插件,其实我并不想加上好用两个字,但是为了表扬插件作者开源免费的崇高精神,我毫不犹豫的加上了好用一词作为赞美. 原本以为

SpringBoot+SpringMVC+MyBatis快速整合搭建

使用过SpringBoot的同学都知道,SpringBoot的pom.xml中的坐标都是按功能导入的,jar包之间的依赖SpringBoot底层已经帮我们做好了,例如我们要整合SprngMVC,只需要导入SpringMVC的起步依赖就可以了,SpringBoot会帮我们导入Spring和SpringMVC整合需要的jar包. SpringBoot是基于Spring4.0设计的,不仅继承了Spring框架原有的优秀特性,而且还通过简化配置来进一步简化了Spring应用的整个搭建和开发过程.另外Sp

Centos 6.6 升级openSSH 远程访问版本(5.3升级7.0源码安装版)

由于服务器Openssh 版本过低,存在不安全因素,所以最近想把服务器都进行升级: 查看当前系统版本为6.6,openssh为5.3版本,此版本启用默认是开启了root远程功能的,因此我能直接通过ROOT进行远程访问. 话不多说,直接上传下载的OPENSSL7.0版本压缩包,需要的可以到http://www.openssh.com官网下载 上传后解压,tar zxf openssh-7.0p1.ta.gz ,然后进cd openssh-7.01p1 目录. ./configure --prefi

Android Studio升级到0.8.1后怎样设置字体大小?

升级到0.8.1后.打开设置字体大小页面.你会发现无论是Default还是Darcula,都不同意你改变字体的大小.事实上这个是由于这两个模式是Android Studio自带模式,所以不同意你修改,你要改的话要自己定义自己的模式.例如以下图: 选中一个你想要的样式,然后点击Save as,然后在弹出的对话框中输入你自定义的样式的名称. 然后再把Scheme name选择成你自己定义的样式,这个时候就能够改了.