Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)));
        };
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading