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 解决方案

尾言

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值