gpt4 book ai didi

spring - 如何为 Joda Period 注入(inject)配置值

转载 作者:行者123 更新时间:2023-12-04 16:51:49 25 4
gpt4 key购买 nike

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

例如。给定以下组件类:

@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

最佳答案

你可以做的是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);
}
}

关于spring - 如何为 Joda Period 注入(inject)配置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34004286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com