-->

LocalDate with Property place holder Spring

2019-07-23 12:27发布

问题:

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)

回答1:

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
..


回答2:

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


回答3:

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

date.A=7/24/17