前言
前一段时间对接第三方有赞云,公司让单独开发一项目来对接同步数据,快速开发当然选择springboot了,但项目开发过程中,调试,发现页面提示框中的提示信息乱码了,才想起来,后台直接返回String类型了,但是没有并没有配置String的消息转换器,导致乱码了。
配置字符串的消息转化器解决问题:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.nio.charset.Charset;
import java.util.List;
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
converters.add(responseBodyConverter());
}
}
细心的同学发现,我这里extends的是WebMvcConfigurationSupport,而没有extends WebConfigAdapter类,是因为springboot2.x使用的是spring5,里边的WebConfigAdapter类已过时,因为jdk8中接口中可以使用default的实体方法,所以可以直接实现WebConfig接口,选择性的重写接口中的方法,因此,WebConfigAdapter包装类就多余了,所以在springboot2.x中标记为已过时。也就说时是说2.x以上的版本有两种方式对spring mvc配置:第一,直接继承 WebMvcConfigurationSupport类;
第二,直接实现WebConfig接口。