Pat*_*Pat 5 configuration spring period jodatime
如何使用@Value注释在我的spring bean中配置Joda-Time Period字段?
例如,给定以下组件类:
@Component
public class MyService {
@Value("${myapp.period:P1D}")
private Period periodField;
...
}
Run Code Online (Sandbox Code Playgroud)
我想使用标准的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
Run Code Online (Sandbox Code Playgroud)
一个不需要任何java代码的简单解决方案是使用Spring Expression Language(SpEL).
(我的例子使用的是java.time.Duration,而不是Joda的东西,但我认为无论如何你都会得到它.)
@Value("#{T(java.time.Duration).parse('${notifications.maxJobAge}')}")
private Duration maxJobAge;
Run Code Online (Sandbox Code Playgroud)
您可以做的是注册一个 SpringConversionService bean 并实现一个适当的转换器。
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1838 次 |
| 最近记录: |