如何为Joda Period注入配置值

时间:2015-11-30 17:20:24

标签: spring configuration jodatime period

如何使用@Value批注在我的spring bean中配置Joda-Time Period 字段?

E.g。给出以下组件类:

@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

3 个答案:

答案 0 :(得分:8)

不需要任何java代码的简单解决方案是使用Spring Expression Language (SpEL)

(我的例子使用的是java.time.Duration而不是Joda的东西,但我认为无论如何你都会得到它。)

    @Value("#{T(java.time.Duration).parse('${notifications.maxJobAge}')}")
    private Duration maxJobAge;

答案 1 :(得分:4)

你可以做的是register a Spring ConversionService bean和implement a proper converter

@Bean
public ConversionServiceFactoryBean conversionService() {
    ConversionServiceFactoryBean conversionServiceFactoryBean = new ConversionServiceFactoryBean();
    Set<Converter<?, ?>> myConverters = new HashSet<>();
    myConverters.add(new StringToPeriodConverter());
    conversionServiceFactoryBean.setConverters(myConverters);
    return conversionServiceFactoryBean;
}

public class StringToPeriodConverter implements Converter<String, Period> {

    @Override
    public Period convert(String source) {
        return Period.parse(source);
    }
}

答案 2 :(得分:1)

另一个不优雅的选择是使用调用解析方法的String setter。

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