LocalDate with Property place holder Spring

2019-07-23 12:39发布

I am working with Spring Boot and property placeholders. I have a property file with the value : date.A=24/07/17. I have a class and I am using the @Value annotation:

@Value("${date.A}")
private LocalDate dateA;

But I am getting the runtime error when running gradle build integrationTest:

Caused by: java.time.format.DateTimeParseException: Text '24/07/17' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 24
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
    at java.time.LocalDate.parse(LocalDate.java:400)

3条回答
小情绪 Triste *
2楼-- · 2019-07-23 12:55

I think you need to write converter for that as follows:

public LocalDate convertToDateObject(String value) throws ConversionException {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    try {
        return LocalDate.parse(value, formatter);

    } catch (DateTimeParseException ex) {
        return null;
    }
}
查看更多
【Aperson】
3楼-- · 2019-07-23 13:07

I would need a closer look at the yml file to give the best answer..But here is my hunch-

The expected format is MM/dd/YY.

Can you please try changing the yml file to something like this

..

date
  A=07/24/17
..
查看更多
虎瘦雄心在
4楼-- · 2019-07-23 13:19

The date should be specified in en_US locale, so you need to swap the month and day:

date.A=7/24/17
查看更多
登录 后发表回答