Search code examples
javaspring-bootdatetimejacksondate-format

Using application property in Spring Boot annotation?


I have the following date field in my DTO class:

@JsonFormat(pattern="dd.MM.yyyy")
private LocalDateTime date;

I define the date format in my application.yml as shown below:

spring:
  jackson:
    date-format: "dd.MM.yyyy"

I am trying to use this format in my DTO field directly like below:

@JsonFormat(pattern="${spring.jackson.date-format}")
private LocalDateTime date;

Is it possible? Or do ı have to add a @Value field like below? I tried but cannot use this dateFormat in my date field.

@Value("${spring.jackson.date-format}")
private String dateFormat;

Solution

  • You have good tips here: https://www.baeldung.com/spring-boot-formatting-json-dates

    Either configure the default format, like

    spring.jackson.date-format=dd.MM.yyyy
    

    or configure the serializer:

    @Configuration
    public class MyJsonConfig {
        @Value("${spring.jackson.date-format}")
        private String dateFormat;
    
        @Bean
        public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
            return builder -> {
                builder.simpleDateFormat(dateTimeFormat);
                builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
                builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateFormat)));
            };
        }
    }