在 Spring Boot 注释中使用应用程序属性?

问题描述 投票:0回答:2

我的 DTO 类中有以下日期字段:

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

我在我的application.yml中定义日期格式如下所示:

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

我正尝试在我的 DTO 字段中直接使用这种格式,如下所示:

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

这可能吗?还是我必须像下面那样添加

@Value
字段?我试过了,但不能在我的日期字段中使用这个
dateFormat

@Value("${spring.jackson.date-format}")
private String dateFormat;
java spring-boot datetime jackson date-format
2个回答
0
投票

这里有很好的提示:https://www.baeldung.com/spring-boot-formatting-json-dates

要么配置默认格式,喜欢

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

或者配置序列化器:

@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)));
        };
    }
}

0
投票
  1. JsonFormat 不是 spring 注解,因此不能使用 spring 表达式语言。
  2. spring.jackson.date-format 为某些类型的日期类定义默认日期格式,您不必在 JsonFormat 中使用此变量,只需定义值即可。有关详细信息,请参见例如https://www.baeldung.com/spring-boot-formatting-json-dates
  3. 如果您想在 spring 中更加灵活,可以为任何类型定义转换器,请参阅同一篇文章。
© www.soinside.com 2019 - 2024. All rights reserved.