如何spring为Joda Period注入配置值

如何spring为Joda Period注入配置值,spring,configuration,jodatime,period,Spring,Configuration,Jodatime,Period,如何使用@Value注释在Springbean中配置Joda时间段字段 例如,给定以下组件类别: @Component public class MyService { @Value("${myapp.period:P1D}") private Period periodField; ... } 我想使用标准ISO8601格式在属性文件中定义句点 我得到这个错误: Caused by: java.lang.IllegalStateException: Cannot convert v

如何使用@Value注释在Springbean中配置Joda时间段字段

例如,给定以下组件类别:

@Component
public class MyService {

  @Value("${myapp.period:P1D}")
  private Period periodField;
...
}
我想使用标准ISO8601格式在属性文件中定义句点

我得到这个错误:

Caused by: java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.joda.time.Period]: no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:302)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:125)
    at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:61)
    ... 35 more
你能做的就是吃豆子

@Bean
公共转换服务工厂bean转换服务(){
ConversionServiceFactoryBean ConversionServiceFactoryBean=新的ConversionServiceFactoryBean();

Set一个不需要任何java代码的简单解决方案是使用

(我的示例使用java.time.Duration,而不是Joda之类的东西,但我想您还是可以理解的。)


另一个并不优雅的选项是使用调用parse方法的字符串设置器

@Value("${myapp.period:P1D}")
public void setPeriodField(String periodField)
{
    if (isBlank(periodField))
        this.periodField= null;
    this.periodField= Duration.parse(periodField);
}

你可能需要注册一个转换器字符串->JodPeriodHanks。你知道这方面的例子吗?很棒的东西。谢谢你的帮助。回答得很好!谢谢你。如果我必须有一个默认值
null
,这需要很多修改,因为java.time.Duration::parse会对
null
参数不满意。
    @Value("#{T(java.time.Duration).parse('${notifications.maxJobAge}')}")
    private Duration maxJobAge;
@Value("${myapp.period:P1D}")
public void setPeriodField(String periodField)
{
    if (isBlank(periodField))
        this.periodField= null;
    this.periodField= Duration.parse(periodField);
}