Spring boot 日期作为YAML属性文件中的映射键

Spring boot 日期作为YAML属性文件中的映射键,spring-boot,yaml,Spring Boot,Yaml,如何使用Spring Boot将日期值从YAML属性绑定到Java映射键 YAML属性文件: settings: calendar: 2018-06-04: 2018-06-25 2018-07-15: 2018-07-20 属性类别: 日历地图的目的是从一个日期转换到另一个日期 @ConfigurationProperties(prefix = "settings") public class CalendarSettings { @DateTimeFormat(p

如何使用Spring Boot将日期值从YAML属性绑定到Java映射键

YAML属性文件:

settings:
  calendar:
    2018-06-04: 2018-06-25
    2018-07-15: 2018-07-20
属性类别:

日历
地图的目的是从一个日期转换到另一个日期

@ConfigurationProperties(prefix = "settings")
public class CalendarSettings {

  @DateTimeFormat(pattern = "yyyy-MM-dd")
  private Map<LocalDate, LocalDate> calendar = new HashMap<>();

  public Map<LocalDate, LocalDate> getCalendar() {
    return calendar;
  }

  public void setCalendar(
    Map<LocalDate, LocalDate> calendar) {
    this.calendar = calendar;
  }
}

我正在努力研究如何在
CalendarSettings.class
中注释日历属性,如果可能的话。或者如何创建某种反序列化程序。

如果在调试模式下运行应用程序,您可能会看到引发以下异常:

Caused by: java.time.format.DateTimeParseException: Text '2018-06-04' could not be parsed at index 4
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) ~[na:1.8.0_162]
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) ~[na:1.8.0_162]
    at java.time.LocalDate.parse(LocalDate.java:400) ~[na:1.8.0_162]
    at org.springframework.format.datetime.standard.TemporalAccessorParser.parse(TemporalAccessorParser.java:69) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.format.datetime.standard.TemporalAccessorParser.parse(TemporalAccessorParser.java:46) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.format.support.FormattingConversionService$ParserConverter.convert(FormattingConversionService.java:200) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
失败的原因是默认解析器()使用本地化的日期转换器将
字符串
映射到
LocalDate
。要解决此问题,您可以编写自己的转换器:

@组件
@配置属性绑定
公共类LocalDateConverter实现转换器{
@凌驾
公共LocalDate转换(字符串时间戳){
返回LocalDate.parse(时间戳);
}
}
如果使用
@ConfigurationPropertiesBinding
注释注册此组件,则在解析应用程序属性时将拾取它。该方法使用
ISO\u LOCAL\u DATE
转换器,在您的情况下,该转换器应该可以正常工作

Caused by: java.time.format.DateTimeParseException: Text '2018-06-04' could not be parsed at index 4
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) ~[na:1.8.0_162]
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) ~[na:1.8.0_162]
    at java.time.LocalDate.parse(LocalDate.java:400) ~[na:1.8.0_162]
    at org.springframework.format.datetime.standard.TemporalAccessorParser.parse(TemporalAccessorParser.java:69) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.format.datetime.standard.TemporalAccessorParser.parse(TemporalAccessorParser.java:46) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.format.support.FormattingConversionService$ParserConverter.convert(FormattingConversionService.java:200) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]