springboot2.0 配置时间格式化不生效问题的解决配置时间格式化不生效问题的解决
主要介绍了springboot2.0 配置时间格式化不生效问题的解决,文中通过示例代码介绍的非常详细,对大家的学
习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
在开发中日期最常打交道的东西之一,但是日期又会存在各式各样的格式,常见的情形就是,从数据库取出的日期往往都是时
间戳(毫秒数)的形式,这个一般情况下是前端不想要的结果,需要进行处理,那在springboot中比较简单:
pom.xml中添加依赖
<!-- 日期格式化 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
要在application.properties进行如下配置:
#日期格式化
spring.jackson.date-format=yyyy-MM-dd
spring.jackson.time-zone=GMT+8
spring.jackson.serialization.write-dates-as-timestamps=false
注:
第1行设置格式
第2行设置时区
第3行表示不返回时间戳,如果为 true 返回时间戳,如果这三行同时存在,以第3行为准即返回时间戳
但是,网上很多人照着做了还是有问题,照样不能格式化,为嘛?
这里大家注意,看看自己的代码有没有因为添加拦截器二创建了一个配置类,该类继承了WebMvcConfigurationSupport,就
是他!以前是用 WebMvcConfigurerAdapter ,springboot 2.0 建议使用 WebMvcConfigurationSupport 。但是在添加拦截器
并继承 WebMvcConfigurationSupport 后会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置!从而导致
所有的Date返回都变成时间戳!
可以采用另外一种方式,在你继承WebMvcConfigurationSupport的子类中添加日期转换的bean
@Configuration
public class Configurer extends WebMvcConfigurationSupport{
@Autowired
HttpInterceptor httpInterceptor;
//定义时间格式转换器
@Bean
public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
converter.setObjectMapper(mapper);
return converter;
}
//添加转换器
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//将我们定义的时间格式转换器添加到转换器列表中,
//这样jackson格式化时候但凡遇到Date类型就会转换成我们定义的格式
converters.add(jackson2HttpMessageConverter());
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
// TODO Auto-generated method stub
registry.addInterceptor(httpInterceptor).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
这样就可解决问题!