Springboot Jackson配置根本方案, 日期格式化, 時區設置生效


當項目集成配置的功能越來越多, 說不准哪個配置就影響到了什么.

比如你啟用了EnableMvC, 默認配置文件配置的一些文件就失效了. 雖然約定大於配置,讓springboot可以極簡化構建, 但不熟悉內部各個組件執行原理會導致我們經常出一些莫名其妙的問題, 比如配置不生效,比如Jackson的日期格式化.

debug了很久, 配置文件不生效, 直接聲明ObjectMapper也不管用. 原因就在於Springboot所謂的簡化是通過一系列的條件配置產生, 比如WebMvcConfigurationSupport, 里面到處都是if-else配置邏輯.
這些配置開關復雜且並不知道散落在哪里.

既然如此, 我直接手動配置好了. 關於springboot json序列化的關鍵是MappingJackson2HttpMessageConverter, 我們需要把springboot默認給配置的converter干掉, 然后放上自己的.

@Configuration
public class RequestHandlerConfig extends WebMvcConfigurationSupport {

    private Logger logger = LoggerFactory.getLogger(RequestHandlerConfig.class);

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //請求上下文初始化攔截器配置
        logger.info("初始化攔截器完成.....");
    }
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Bean
    public ObjectMapper jacksonObjectMapperCustomization() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TimeZone timeZone = TimeZone.getTimeZone("Asia/Shanghai");
        format.setTimeZone(timeZone);

        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
                .timeZone(timeZone)
                .dateFormat(format);

        return builder.build();
    }
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.removeIf(c -> c instanceof MappingJackson2HttpMessageConverter);
        converters.add(new MappingJackson2HttpMessageConverter(jacksonObjectMapperCustomization()));
    }

}

讓LocalDateTime格式化:


import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Ryan Miao 01399596
 * @date 2021/1/28 16:35
 */
@Configuration
public class DateConfiguration {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer enumCustomizer() {
        return builder -> builder.deserializerByType(LocalDateTime.class,
            new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
            .deserializerByType(LocalDate.class,
                new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
            .serializerByType(LocalDateTime.class,
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
            .serializerByType(LocalDate.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
            ;
    }

    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = formatter.format(LocalDateTime.now());
        System.out.println(format);
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM