springboot 2.0 配置時間格式化不生效問題

在application.properties進行以下配置:java

#日期格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.jackson.serialization.write-dates-as-timestamps=false

注:spring

  • 第1行設置格式
  • 第2行設置時區
  • 第3行表示不返回時間戳,若是爲 true 返回時間戳,若是這三行同時存在,以第3行爲準即返回時間戳

可是,網上不少人照着作了仍是有問題,照樣不能格式化,爲嘛?
這裏你們注意,看看本身的代碼有沒有由於添加攔截器而建立了一個配置類,該類繼承了WebMvcConfigurationSupport,就是他!之前是用 WebMvcConfigurerAdapterspringboot 2.0 建議使用 WebMvcConfigurationSupport 。可是在添加攔截器並繼承 WebMvcConfigurationSupport後會覆蓋@EnableAutoConfiguration關於WebMvcAutoConfiguration的配置!從而致使全部的Date返回都變成時間戳!
能夠採用另一種方式,在你繼承WebMvcConfigurationSupport的子類中添加日期轉換的beanspringboot

@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);
    }   
}

或者能夠實現WebMvcConfigurer接口app

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
                .allowCredentials(true).maxAge(3600);
    }
}

個人博客即將同步至騰訊雲+社區,邀請你們一同入駐:https://cloud.tencent.com/developer/support-plan?invite_code=1jx0g2a8qtn8eide

本文同步分享在 博客「吟風者」(JianShu)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。svg

相關文章
相關標籤/搜索