问题
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);
}
}