我正在尝试使用以下代码从spring的application.properties中解析LocalTime:
@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
知道我做错了什么吗?谢谢。
为了将日期注入@Value,使用了Spring Expression Language(SpEL),例如:
@Value(“#{new java.text.SimpleDateFormat(‘${aTimeFormat}’).parse(‘${aTimeStr}’)}”)
Date myDate;
在您的情况下,您直接注入Date值而没有提供格式化程序,因此它不知道要解析为哪种格式,不定义具有该格式的新属性,并使用该格式化程序来解析该值,如上面的示例,它将被注射。您的application.properties属性应类似于:
aTimeStr=21:16:46
aTimeFormat=HH:mm:ss
如果使用@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"));
}
}
请参阅https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html以获取DateTimeFormatter选项的列表。
[如果您宁愿坚持[C0],那么您就很接近了:
@Value
来源:
@Value("#{T(java.time.LocalTime).parse('${app.myDateTime}', T(java.time.format.DateTimeFormatter).ofPattern('hh:mm:ss'))}")
Spring: create LocalDate or LocalDateTime from @Value parameter