@DateTimeFormat注解

@DateTimeFormat注解_第1张图片

 @DateTimeFormat注解位于spring-context-5.0.10.RELEASE.jar包中

import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;

public class User {

    //姓名
    private String name;
    //出生日期
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}
package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/demo")
public class DempoController {
    
    @PostMapping("/testDateTimeFormat")
    @ResponseBody
    public void testDateTimeFormat(@RequestBody(required=true) User user){
        System.out.println(user.toString());
    }
}

请求报文:

@DateTimeFormat注解_第2张图片

输出结果:

User{name='姓名', birthday=Tue Jan 01 08:00:00 CST 2019}

从输出结果来看,@DateTimeFormat注解会自动将请求报文中的字符串转换为指定格式的Date类型的数据,但是对于birthday字段会默认添加赋上08:00:00,实际上这部分并不是我想要的,因此还是觉得该注解在SpringBoot中使用还是不够友好,不建议使用该注解

你可能感兴趣的:(Spring,Boot)