我的 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;
这里有很好的提示: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)));
};
}
}