如何通过 application.properties 注入日期值

Joh*_*ohn 3 java spring-boot

有没有办法在 Spring-Boot 项目中通过 application.properties 注入日期值。像这样。

@Component
@ConfigurationProperties(prefix = "foo")
public Class FooConfiguration {
    private Date startTime;
    //getter and setter
}
foo.startTime="2019-03-18 00:00:00"
Run Code Online (Sandbox Code Playgroud)

noi*_*ale 5

您可以为配置属性类配置自定义转换器,如下所示:

日期转换器.java

@Component
@ConfigurationPropertiesBinding
public class DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        if (source == null) {
            return null;
        }
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(source);
    }
}
Run Code Online (Sandbox Code Playgroud)

应用程序属性

foo.start-time=2019-03-18 00:00:00
Run Code Online (Sandbox Code Playgroud)

  • 不适用于 spring-boot `2.7.0` (2认同)