当前位置: 首页 > news >正文

基于SpringBoot格式化实体的时间类型以及静态注入依赖

一. 场景描述

在进行前后端交互时,发现实体的LocalDateTime返回的格式是这样的:

image-20250124173445264

这不符合我们日常习惯的格式 “年-月-日 时:分:秒”,于是上网学习了前辈
励碼的文章SSM项目中LocalDateTime格式化最佳实践_localdatetime 格式化-CSDN博客解决了问题。

二. 解决方案:

用到的和 jackson 相关的依赖有:

<!--	Json序列化(ObjectMapper)	-->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.18.1</version>
</dependency>
<!--用于适配JAVA的时间类型(比如LocalDateTime)-->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 -->
<dependency><groupId>com.fasterxml.jackson.datatype</groupId>	<artifactId>jackson-datatype-jsr310</artifactId><version>2.18.2</version>
</dependency>

2.1 创建配置类

千万别忘了注册 JavaTimeModule(),否则会报错转换不了 LocalDateTime类型

/*** @author yamu* @version 1.0* @description 配置响应的 Json 字符串的时间格式* @date 2025/1/24 9:54*/
@Configuration
public class JacksonConfig {public static final String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";@Bean(name = "myObjectMapper")public ObjectMapper myObjectMapper() {ObjectMapper objectMapper = new ObjectMapper();//适用于java8的时间模块JavaTimeModule javaTimeModule = new JavaTimeModule();//年-月-日 时:分:秒DateTimeFormatter localDateTimeFormatter = DateTimeFormatter.ofPattern(DEFAULT_DATETIME_FORMAT);javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(localDateTimeFormatter));javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(localDateTimeFormatter));//年-月-日DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT);javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(dateFormatter));javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(dateFormatter));//时:分:秒DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT);javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(timeFormatter));javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(timeFormatter));//注册时间模块(不注册的话,会报错Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling... )objectMapper.registerModule(javaTimeModule);// 配置其他特性objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));//设置东八区return objectMapper;}
}

2.2 在响应类中注册

这里有个注意点,由于我的响应类是通过R.success(T)去返回给前端的,所以自定义的ObjectMapper需要静态注入,但是@Autowired是不支持自动静态注入的,所以我定义了一个工具类去进行注入。

/*** @description: 自定义消息响应类* @author yamu* @date 2024/11/12 11:22* @version 1.0*/
@Data
public class R<T> {private Integer code; //0失败,1成功private String message; //错误信息private T data; //数据public static ObjectMapper objectMapper;//静态代码块注入JacksonConfig定义的objectMapperstatic{objectMapper =  ObjectMapperUtil.getObjectMapper();}/*** @description: 带返回值成功* @param: object* @returns:  R<T>* @author yamu* @date: 2024/11/12 11:24*/public static <T> String success(T object) {R<T> r = new R<T>();r.data = object;r.code = 1;try {return objectMapper.writeValueAsString(r);} catch (JsonProcessingException e) {throw new RuntimeException(e);}}
}

2.3 定义工具类静态注入ObjectMapper

/*** @author yamu* @version 1.0* @description 获取自定义序列化器的 ObjectMapper* @date 2025/1/24 17:06*/
@Component
public class ObjectMapperUtil implements ApplicationContextAware {private static ApplicationContext context;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {context = applicationContext;}public static ObjectMapper getObjectMapper() {return (ObjectMapper) context.getBean("myObjectMapper");}
}	public static ObjectMapper getObjectMapper() {return (ObjectMapper) context.getBean("myObjectMapper");}
}	

结果如下:

image-20250124174955587

http://www.lryc.cn/news/526910.html

相关文章:

  • 技术总结:FPGA基于GTX+RIFFA架构实现多功能SDI视频转PCIE采集卡设计方案
  • Flink读写Kafka(Table API)
  • 【Numpy核心编程攻略:Python数据处理、分析详解与科学计算】1.2 ndarray解剖课:多维数组的底层实现
  • 冯诺依曼架构和哈佛架构的主要区别?
  • Gurobi基础语法之字典
  • ceph新增节点,OSD设备,标签管理(二)
  • 利用metaGPT多智能体框架实现智能体-2
  • Hadoop 与 Spark:大数据处理的比较
  • Django 日志配置实战指南
  • 传输层协议TCP与UDP:深入解析与对比
  • doris:JSON导入数据
  • Ubuntu18.04 搭建DHCP服务器
  • Spring Boot 邂逅Netty:构建高性能网络应用的奇妙之旅
  • 【云安全】云原生-Docker(五)容器逃逸之漏洞利用
  • 九、CSS工程化方案
  • gradle创建springboot单项目和多模块项目
  • Vue实现div滚动,并且支持top动态滚动
  • Elasticsearch 中,分片(Shards)数量上限?副本的数量?
  • Unity入门1
  • 网络模型简介:OSI七层模型与TCP/IP模型
  • 软件测试压力太大了怎么办?
  • 微信小程序-点餐(美食屋)02开发实践
  • 转换算术表达式
  • 99.17 金融难点通俗解释:归母净利润
  • 【Flutter】旋转元素(Transform、RotatedBox )
  • MYSQL学习笔记(六):聚合函数、sql语句执行原理简要分析
  • thinkphp6+swoole使用rabbitMq队列
  • 大模型开发 | RAG在实际开发中可能遇到的坑
  • mybatis是什么?有什么作用?mybatis的简单使用
  • 求平均年龄(信息学奥赛一本通-1059)