第一种方式继承WebMvcConfigurerAdapter或者继承WebMvcConfigurationSupport。复写configureMessageConverters方法
代码:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.PrettyFormat
);
fastJsonConfig.setDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS);
List<MediaType> fastMediaType = new ArrayList<>();
fastMediaType.add(MediaType.APPLICATION_JSON_UTF8);
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaType);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastJsonHttpMessageConverter);
}
注意一点,springboot2.0以后WebMvcConfigurerAdapter已经被废弃,需要继承WebMvcConfigurationSupport,但是继承WebMvcConfigurationSupport会导致springboot的application.properties/application.yml自动配置失效,配置了拦截器的话静态资源无法访问。需要自己配置静态资源
网上找的资料代码:
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
路径根据自己项目配置
还有一种方式是实现WebMvcConfigurer,这种没有WebMvcConfigurationSupport的问题
我用的WebMvcConfigurerAdapter springboot版本的是1.4.3,就不需要再额外配置了
第二种方式是无需继承或者实现,手动配置即可
再新建的类里面配置bean
代码:
package com.pinyu.system.global.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.pinyu.system.utils.DateUtils;
/**
* @author ypp 创建时间:2018年11月29日 下午5:49:11
* @Description: TODO(用一句话描述该文件做什么)
*/
@Configuration
public class ResponseJsonConfig {
// 配置返回json为fastjson,可以放在任何配置的地方,能被spring扫描就行
@Bean
public HttpMessageConverters fastJsonConfigure() {
// 1.需要先定义一个convert 转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 2.添加fastJson的配置信息,比如,是否需要格式化返回的json数据
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS);
// 处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
// 3.在convert中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
return new HttpMessageConverters(fastConverter);
}
}
类上面要贴上@Configuration注解,表示springboot在启动的时候纳入配置范围
@SpringBootConfiguration和@Configuration一个意思,但官方建议是使用@SpringBootConfiguration