Bootstrap

基于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定义的objectMapper
    static
    {
        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;

    @Override
    public 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

;