【springboot】@RestController不返回json default-property-inclusion: non_null不起作用

最近开发中遇到个比较奇怪的现象,一直以来我们都是用RestController返回json,
default-property-inclusion: non_null把null值过滤,但是突然间有个项目,
这样的配置和注解就失效了,只要代码没报错,返回了结果,那就不该从自身写的sql查询代码找问题,
同样的代码在之前项目可以,新项目不行,就要考虑架构问题,是不是引入了什么,把配置给覆盖了。

原因排查:

全局查找 发现有个类继承了 WebMvcConfigurationSupport ,而在spring boot官方文档中有提示,在这里插入图片描述
我们可以写个@EnableWebMvc 点进去看看,里面import了一个DelegatingWebMvcConfiguration
在这里插入图片描述
在这里插入图片描述

而我们可以在WebMvcAutoConfiguration中看到,@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
也就是说 当不存在 WebMvcConfigurationSupport 的时候 ,WebMvcAutoConfiguration自动配置才会生效
在这里插入图片描述

结论:

文档提示不能写@EnableWebMvc注解 但它并不是最终原因,因为@EnableWebMvc最终用到了WebMvcConfigurationSupport,也就是说WebMvcConfigurationSupport才是问题根本所在


解决方法

所以 如果项目中,继承WebMvcConfigurationSupport的类 没什么很大作用 或者可以其它方式替代,我们可以不再使用这个类,如果这个类是必不可少的,或者不确定用途,我们只好通过注解的形式,完成返回json及过滤空值的功能:
在controller层 RequestMapping或GetMapping等注解中加上格式,强制转成json:
@GetMapping(headers = “Accept=application/json” ,produces =“application/json;charset=UTF-8” )

在实体类中加上注解 @JsonInclude(JsonInclude.Include.NON_NULL)

おすすめ

転載: blog.csdn.net/qq_36268103/article/details/115544633