优秀的编程知识分享平台

网站首页 > 技术文章 正文

启动时报Failed to bind properties under 'xxx' to java.util.Date异常

nanyue 2024-08-04 16:59:07 技术文章 7 ℃


问题

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

Tags:

最近发表
标签列表