SpringBoot2 版本中spring.jackson.date-format設置以後不生效的速效解決方法

spring.jackson.date-format 這個屬性在spring boot 1.x中有用,但是當你項目升級到spring boot2.x 以後,時間格式化變無效了

網上說的原因分析:
               spring boot2 中推薦使用的攔截器爲 WebMvcConfigurationSupport 
               spring boot1.x 中使用的是 WebMvcConfigurerAdapter ,但是在添加攔截器並繼承WebMvcConfigurationSupport後會覆蓋@EnableAutoConfiguration關於WebMvcAutoConfiguration的配置!從而導致所有的Date`返回都變成時間戳!

        網上很多方案說棄用 WebMvcConfigurationSupport 改用 implements WebMvcConfigurer 這種方案

        其實集成WebMvcConfigurationSupport  以後,直接實現 extendMessageConverters 方法即可,代碼如下

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {
	
	@Value("${spring.jackson.date-format}")
	private String dateFormatPattern;
	
	@Value("${spring.jackson.time-zone}")
	private String timeZone;
	
	@Override
	protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
		MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
		ObjectMapper objectMapper = converter.getObjectMapper();
		// 生成JSON時,將所有Long轉換成String
		SimpleModule simpleModule = new SimpleModule();
		simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
		simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
		objectMapper.registerModule(simpleModule);
		// 時間格式化
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		//這個可以引用spring boot yml 裏的格式化配置和時區配置
		objectMapper.setDateFormat(new SimpleDateFormat(dateFormatPattern));
		objectMapper.setTimeZone(TimeZone.getTimeZone(timeZone));
		// 設置格式化內容
		converter.setObjectMapper(objectMapper);
		converters.add(0, converter);
		super.extendMessageConverters(converters);
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章