Spring boot锦集(一):日期格式化的两种方式 | 在Bean对象的日期对象上添加注解 | 对Bean的日期格式统一处理

前言

在日常开发中,日期类是经常使用的,本篇提供两种日期格式的配法,以供不时之需。

方式一、单独在Bean对象的日期对象上添加注解

该方法省时省力,相当的Nice

  @com.fasterxml.jackson.annotation.JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
   private Date createTime;

方式二、创建配置类,对Bean的日期格式统一处理

1、代码片段

package com.example.demo.conf;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;

/** 
 * @create 2022-10-06 12:27
 * @describe
 */
@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        System.out.println("日期格式转换,被调用了");//如果这行代码,在项目启动时没有被控制台打印,说明该配置未生效
        ObjectMapper objectMapper = new ObjectMapper();
        // 自定义日期转换格式
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        return objectMapper;
    }
}

2、注意事项

如果添加该配置类后,配置一直未生效,可以尝试在对应的Controller类上添加@ComponentScan注解。

package com.example.demo.controller;

import com.example.demo.bean.User;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xyp
 * @create 2022-10-04 16:33
 * @describe
 */
@RestController
@ComponentScan(basePackages={"com.example.demo.*"})
public class UserController {
    @PostMapping("/getUser")
    public User getUser(@RequestBody User user) {
        System.out.println(user.getCreateTime().toString());
        // 将 user 再以 Json 的形式返回
        return user;
    }
}

效果展示

postman效果展示,如果你遇到了415错误,点击这里“status“: 415 解决方案

尾言

知识在于积累,不积跬步无以至千里,加油!