In a spring project, I'd like to create a LocalDate
from an @Autowired
constructor parameter whose value is in a .properties
file. Two things I'd like to do:
1. If the property file contains the property my.date
, the parameter should be created by parsing the property value
When the property is set, and when I use the following:
@DateTimeFormat(pattern = "yyyy-MM-dd") @Value("${my.date}") LocalDate myDate,
...
I get this error: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.time.LocalDate': no matching editors or conversion strategy found
I have also used the iso = ...
to use an ISO date with the same result.
2. If the property is not in the properties file, the parameter should be created using LocalDate.now()
I tried using a default value as such:
@Value("${my.date:#{T(java.time.LocalDate).now()}}") LocalDate myDate,
...
But I get the same error.
Forgive my ignorance with Spring, but how can I achieve the two objectives here?
LocalDate – represents a date (year, month, day) LocalDateTime – same as LocalDate, but includes time with nanosecond precision.
The easiest way to create an instance of the LocalDateTime class is by using the factory method of(), which accepts year, month, day, hour, minute, and second to create an instance of this class. A shortcut to create an instance of this class is by using atDate() and atTime() method of LocalDate and LocalTime class.
LocalDate is an immutable class that represents Date with default format of yyyy-MM-dd. We can use now() method to get the current date. We can also provide input arguments for year, month and date to create LocalDate instance.
Parse String to LocalDate The LocalDate class has two overloaded parse() methods to convert a string to a LocalDate instance. Use first method if the string contains date in ISO_LOCAL_DATE pattern i.e. yyyy-MM-dd. This is default pattern of local dates in Java.
I know two ways. One is generic for any object - to use @Value annotation on custom setter
@Component
public class Example {
private LocalDate localDate;
@Value("${property.name}")
private void setLocalDate(String localDateStr) {
if (localDateStr != null && !localDateStr.isEmpty()) {
localDate = LocalDate.parse(localDateStr);
}
}
}
The second is for LocalDate/LocalDateTime
public class Example {
@Value("#{T(java.time.LocalDate).parse('${property.name}')}")
private LocalDate localDate;
}
Sample property:
property.name=2018-06-20
Spring Boot 2.5, works perfect:
application.yaml
my.date: 2021-08-14
my.time: "11:00"
@Service
public class TestService {
@Value("${my.date}")
@DateTimeFormat(pattern = "yyyy-MM-dd")
LocalDate myDate;
@Value("${my.time}")
@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
LocalTime myTime;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With