스프링 부트에서 전역 시간 형식화를 위한 3가지 방법

@JsonFormat 어노테이션

개별 필드에 적용되는 방식으로, 전역 설정이 아닌 특정 엔티티의 시간 필드만 포맷팅합니다. DTO 클래스의 필드에 직접 어노테이션을 선언하여 사용합니다.

@Data
public class PaymentRecord {

    @JsonFormat(locale = "ko", timezone = "Asia/Seoul", pattern = "yyyy-MM-dd")
    private LocalDateTime paymentDate;

    @JsonFormat(locale = "ko", timezone = "Asia/Seoul", pattern = "yyyy-MM-dd HH:mm")
    private Date modificationTime;
}

@JsonComponent 어노테이션

전역 시간 포맷팅을 위한 추천 방식으로, Date와 LocalDateTime 타입을 모두 처리할 수 있습니다. 구성 클래스에 커스텀 직렬화 설정을 구현합니다.

@JsonComponent
public class DateTimeConfigurer {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm}")
    private String formatPattern;

    @Bean
    public Jackson2ObjectMapperCustomizer objectMapperCustomizer() {
        return mapper -> {
            DateFormat df = new SimpleDateFormat(formatPattern);
            df.setTimeZone(TimeZone.getTimeZone("Asia/Seoul"));
            mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                  .setDateFormat(df);
        };
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return builder -> builder.serializers(
            new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(formatPattern))
        );
    }
}

개별 필드에 @JsonFormat을 추가하면 전역 설정을 재정의할 수 있습니다.

@Configuration 어노테이션

ObjectMapper를 직접 구성하는 방식으로, Date와 LocalDateTime에 대한 커스텀 직렬화/역직렬화를 구현합니다. 이 방식을 사용하면 필드 레벨의 @JsonFormat 설정이 무시됩니다.

@Configuration
public class MapperConfiguration {

    private static final String TIME_PATTERN = "yyyy-MM-dd HH:mm";

    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        JavaTimeModule module = new JavaTimeModule();
        module.addSerializer(LocalDateTime.class, new CustomLocalDateTimeSerializer());
        module.addDeserializer(LocalDateTime.class, new CustomLocalDateTimeDeserializer());
        mapper.registerModule(module);
        return mapper;
    }

    private static class CustomLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            gen.writeString(value.format(DateTimeFormatter.ofPattern(TIME_PATTERN)));
        }
    }

    private static class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
            return LocalDateTime.parse(p.getText(), DateTimeFormatter.ofPattern(TIME_PATTERN));
        }
    }
}

태그: Spring Boot Jackson Date Formatting LocalDateTime Java Date

5월 29일 08:52에 게시됨