本文章僅供小編學(xué)習(xí)使用,如有侵犯他人版權(quán),請聯(lián)系小編撤回或刪除
首先我們需要明白一個概念:
springboot中很多配置都是使用了條件注解進(jìn)行判斷一個配置或者引入的類是否在容器中存在,如果存在會如何,如果不存在會如何。
也就是說,有些配置會在springboot中有默認(rèn)配置,前提是你沒有配置,這樣來起到簡化配置作用。如果你配置了,容器就不會為你再去默認(rèn)配置。
配置消息轉(zhuǎn)化器的兩種方法:
方法一:自定義消息轉(zhuǎn)化器,只需要在@Configuration的類中添加消息轉(zhuǎn)化器的@bean加入到Spring容器,就會被Spring Boot自動加入到容器中。
/**
* @program: workspace
* @description: 自定義消息轉(zhuǎn)換器
* @author: 劉宗強(qiáng)
* @create: 2019-08-28 15:32
**/
@Configuration
public class WebMvcConfigurerAdapter {
/**
* 自定義字符串轉(zhuǎn)換器
* @return
*/
@Bean
public StringHttpMessageConverter stringHttpMessageConverter(){
StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
return converter;
}
/**
* 自定義fastJson轉(zhuǎn)換器
* @return
*/
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters(){
//1.需要定義一個convert轉(zhuǎn)換消息的對象;
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//2:添加fastJson的配置信息;
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//3處理中文亂碼問題
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
//4.在convert中添加配置信息.
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
return new HttpMessageConverters(converter);
}
}
方法二:請查看文章底部原文