問題
springboot2項目啟動時報Failed to bind properties under 'oss.buy-deadline' to java.util.Date異常;
在 application.yml 中的配置項,使用 Date 類型字段接收,項目啟動時報錯,如下:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'ossProperties': Could not bind properties to 'OssProperties' : prefix=aliyun.oss, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'oss.buy-deadline' to java.util.Date
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'ossProperties': Could not bind properties to 'OssProperties' : prefix=aliyun.oss, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'oss.buy-deadline' to java.util.Date
解決辦法
自定義轉換器
必須加上 @ConfigurationPropertiesBinding 注解,不然轉換器是在啟動後使用,項目啟動時還是會報錯
@Component
@ConfigurationPropertiesBinding
public class String2DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
if (StringUtils.isEmpty(source)) {
return null;
}
return DateUtils.parseWithTime(source);
}
}