Разбор LocalTime с использованием языка выражения весны из application.properties - PullRequest
0 голосов
/ 23 октября 2019

Я пытаюсь проанализировать LocalTime из приложения application.properties в Spring со следующим кодом:

@Value("#{ T(java.time.LocalTime).parse('${app.myDateTime}')}")
private LocalTime myDateTime;

в файле application.properties. Я определил свойство, подобное этому:

app.myDateTime=21:45:00

Сообщение об ошибке:

Failed to bind properties under 'app.my-date-time' to java.time.LocalTime:

Property: app.my-date-time
Value: 21:45:00
Origin: class path resource [application.properties]:44:15
Reason: failed to convert java.lang.String to @org.springframework.beans.factory.annotation.Value java.time.LocalTime

Есть идеи, что я не так сделал? Спасибо.

Ошибка в режиме отладки:

Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.time.LocalTime] for value '21:45:00'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [21:45:00]
    at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:47)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:191)
    at org.springframework.boot.context.properties.bind.BindConverter$CompositeConversionService.convert(BindConverter.java:170)
    at org.springframework.boot.context.properties.bind.BindConverter.convert(BindConverter.java:96)
    at org.springframework.boot.context.properties.bind.BindConverter.convert(BindConverter.java:88)
    at org.springframework.boot.context.properties.bind.Binder.bindProperty(Binder.java:313)
    at org.springframework.boot.context.properties.bind.Binder.bindObject(Binder.java:258)
    at org.springframework.boot.context.properties.bind.Binder.bind(Binder.java:214)
    ... 210 common frames omitted
Caused by: java.lang.IllegalArgumentException: Parse attempt failed for value [21:45:00]
    at org.springframework.format.support.FormattingConversionService$ParserConverter.convert(FormattingConversionService.java:206)
    at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:41)
    ... 217 common frames omitted
Caused by: java.time.format.DateTimeParseException: Text '21:45:00' could not be parsed at index 5
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalTime.parse(LocalTime.java:441)
    at org.springframework.format.datetime.standard.TemporalAccessorParser.parse(TemporalAccessorParser.java:72)
    at org.springframework.format.datetime.standard.TemporalAccessorParser.parse(TemporalAccessorParser.java:46)
    at org.springframework.format.support.FormattingConversionService$ParserConverter.convert(FormattingConversionService.java:200)
    ... 218 common frames omitted

Ответы [ 3 ]

1 голос
/ 23 октября 2019

Для вставки дат в @Value используется язык выражений Spring (SpEL), например:

@Value(“#{new java.text.SimpleDateFormat(‘${aTimeFormat}’).parse(‘${aTimeStr}’)}”)
Date myDate;

В вашем случае вы напрямую вводите значение даты без предоставления средства форматирования, поэтомуНе знаю, какой формат анализировать, определить новое свойство с форматом и использовать этот форматер для анализа значения, как в примере выше, оно будет введено. Свойства вашего application.properties должны быть такими:

aTimeStr=21:16:46
aTimeFormat=HH:mm:ss
0 голосов
/ 24 октября 2019

Я проверял это на весенней загрузке 2.1.5 с jdk-11

@Value("#{ T(java.time.LocalTime).parse('${app.myDateTime}',T(java.time.format.DateTimeFormatter).ISO_LOCAL_TIME)}")
private LocalTime timeValue;   //21:45
0 голосов
/ 23 октября 2019

Вариант 1 - используйте @ConfigurationPropertiesBinding

Если вы используете @ConfigurationProperties для загрузки своих свойств, вы можете использовать @ConfigurationPropertiesBinding для привязки пользовательских конвертеров к Spring:

@Component
@ConfigurationPropertiesBinding
public class LocalTimeConverter implements Converter<String, LocalTime> {
  @Override
  public LocalTime convert(String source) {
      if(source==null){
          return null;
      }
      return LocalDate.parse(source, DateTimeFormatter.ofPattern("HH:mm:ss"));
  }
}

enter image description here

Вариант 2 - используйте @Value

Если вы предпочитаете придерживаться @Value, тогда вы были довольно близки:

@Value("#{T(java.time.LocalTime).parse('${app.myDateTime}', T(java.time.format.DateTimeFormatter).ofPattern('HH:mm:ss'))}")

См. https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html для списка параметров DateTimeFormatter.

Источники:

...