技术文摘
3 种 Springboot 全局时间格式化的方法,告别重复代码
在开发 Spring Boot 应用时,时间格式化是一个常见的需求。为了避免在每个需要处理时间的地方重复编写格式化代码,我们可以采用以下三种全局时间格式化的方法。
方法一:使用 @JsonFormat 注解
@JsonFormat 注解可以方便地对返回的 JSON 数据中的时间字段进行格式化。在实体类的时间字段上添加 @JsonFormat 注解,并指定相应的格式字符串,例如:
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class YourEntity {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
// 其他字段和方法
}
这样,在将实体类转换为 JSON 数据时,时间字段会按照指定的格式进行输出。
方法二:自定义 HttpMessageConverter
通过自定义 HttpMessageConverter 可以实现更灵活的时间格式化。首先创建一个继承自 AbstractJackson2HttpMessageConverter 的类:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import java.text.SimpleDateFormat;
public class CustomJsonHttpMessageConverter extends AbstractJackson2HttpMessageConverter {
public CustomJsonHttpMessageConverter() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
super(objectMapper, MediaType.APPLICATION_JSON);
}
}
然后在配置类中注册这个自定义的 HttpMessageConverter:
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new CustomJsonHttpMessageConverter());
}
}
方法三:配置 spring.jackson.date-format
在 application.properties 或 application.yml 文件中配置 spring.jackson.date-format 属性:
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
这种方式可以全局设置时间的格式化格式。
通过以上三种方法,我们可以有效地实现 Spring Boot 全局时间格式化,减少重复代码,提高开发效率和代码的可维护性。在实际项目中,根据具体的需求和场景选择合适的方法,让时间处理变得更加简洁和规范。
TAGS: SpringBoot 开发技巧 时间格式化方法 告别重复代码
- 你了解 HTML、CSS、JS、Services、PHP、ASP.NET 的来源吗?
- 怎样写出令同事难以维护的代码?
- 探秘网络工具中的“瑞士军刀”
- 历经诸多坑洼,为你呈上 H5 交互页面跳转方式汇总
- 前端基础:实现两个浏览器窗口通信的方式及方法
- JavaScript 基础:JS 内存管理、内存泄漏与垃圾回收解析
- Git 操作错误后的应对之策,收藏此文档
- Redis 在海量数据与高并发中的优化实践直接上手
- 给女朋友转账促使我思考分布式事务
- Spring 中有关 Null 的这些事,你真的清楚吗?
- 决战紫禁之巅:深度学习框架 Keras 与 PyTorch 之比较
- Python 十大图像优化工具,尽显简洁魅力
- 彻底搞懂写缓冲(Change Buffer)
- 9 款免费的 Java 流程监控工具
- 阿里巴巴为何要求慎用 ArrayList 中的 subList 方法