最安全做法使用bean替代默认转换器方法
@Configuration
public class MyConfiguration {
@Bean
public HttpMessageConverters customConverters() {
List<HttpMessageConverters> converters = new ArrayList<>();
// 1、需要先定义一个convert转换消息的对象;
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 2、添加fastjson的配置信息,比如 是否要格式化返回json数据
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
// 3、在convert中添加配置信息.
fastConverter.setFastJsonConfig(fastJsonConfig);
// 4、将convert添加到converters当中.
converters.add(fastConverter);
return new HttpMessageConverters(true, converters);
}
}
第二种做法
实现WebMvcConfigurer,需要将jackson依赖移除才能生效(缺点不能加入jackson,gson等,否则spring会自动装配)
@Configuration
public class SpringMvcConfigure implements WebMvcConfiguration{
/**
* 配置消息转换器
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//自定义配置...
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.QuoteFieldNames,
SerializerFeature.WriteEnumUsingToString,
/*SerializerFeature.WriteMapNullValue,*/
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect);
fastJsonHttpMessageConverter.setFastJsonConfig(config);
converters.add(fastJsonHttpMessageConverter);
}
}
第三种实现父类,缺点很明显,完全接管的springmvc,默认配置全部失效,需要重新自己配置
@Configuration
public class SpringMvcConfigure extends WebMvcConfigurationSupport{
/**
* 配置消息转换器
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//自定义配置...
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.QuoteFieldNames,
SerializerFeature.WriteEnumUsingToString,
/*SerializerFeature.WriteMapNullValue,*/
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect);
fastJsonHttpMessageConverter.setFastJsonConfig(config);
converters.add(fastJsonHttpMessageConverter);
supper.configureMessageConverters(converters);
}
}
参考附录
https://blog.csdn.net/bluuusea/article/details/79665440
https://segmentfault.com/a/1190000015975405
https://github.com/spring-projects/spring-boot/issues/12389
来源:https://blog.csdn.net/BBsatan/article/details/98748229