spring boot 替換預設的jackjson返回fastjson
阿新 • • 發佈:2018-12-11
第一種方式繼承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