SpringBoot+MyBatis Plus对Map中Date格式转换的处理( 三 )

  • public class Event {

  •    public String name;

  •    @JsonSerialize(using = CustomDateSerializer.class)

  •    public Date eventDate;

  • }

  • 2. 修改 ObjectMapper通过 ObjectMapper.setDateFormat() 设置日期格式, 改变默认的日期序列化反序列化行为. 这种方式只对调用此ObjectMapper的场景有效
    1. private static ObjectMapper createObjectMapper() {

    2. ObjectMapper objectMapper = new ObjectMapper();

    3. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    4. objectMapper.setDateFormat(df);

    5. return objectMapper;

    6. }

    因为 ObjectMapper 一般是当作线程安全使用的, 而 SimpleDateFormat 并非线程安全, 在这里使用是否会有问题? 关于这个疑虑, 可以查看 这个链接
    @StaxMan: I am a bit concerned if ObjectMapper is still thread-safe after ObjectMapper#setDateFormat() is called. It is known that SimpleDateFormat is not thread safe, thus ObjectMapper won't be unless it clones e.g. SerializationConfig before each writeValue() (I doubt). Could you debunk my fear? – dma_k Aug 2, 2013 at 12:09
    DateFormat is indeed cloned under the hood. Good suspicion there, but you are covered. – StaxMan Aug 2, 2013 at 19:43
    3. 修改 SpringBoot 配置增加配置 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss, 这种配置, 只对 Spring BeanFactory 中创建的 Jackson ObjectMapper有效, 例如 HTTP 请求和响应中对 Date 类型的转换
    1. spring:

    2.  ...

    3.  jackson:

    4.    date-format: yyyy-MM-dd HH:mm:ss

    整体方案国内项目, 几乎都会希望落库时日期就是日期的样子(方便看数据库表), 所谓日期的样子就是yyyy-MM-dd HH:mm:ss格式的字符串. 如果怕麻烦, 就通通都用这个格式了.
    这样统一存在的隐患是丢失毫秒部分. 这个问题业务人员基本上是不会关心的. 如果需要, 就在格式中加上.
    第一是 Spring 配置, 这样所有的请求响应都统一了
    1. spring:

    2.  ...

    3.  jackson:

    4.    date-format: yyyy-MM-dd HH:mm:ss

    第二是定义一个工具类, 把 ObjectMapper 自定义一下, 这样所有手工转换的地方也统一了, 注意留一个getObjectMapper()方法

      经验总结扩展阅读