How to spring enter configuration value for Joda period

How can I use the @Value annotation to configure the Joda-Time period field in my spring bean?

eg. Given the following class of components:

@Component public class MyService { @Value("${myapp.period:P1D}") private Period periodField; ... } 

I want to use the standard ISO8601 format to define the period in a property file.

I get this error:

 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 
+5
source share
3 answers

What you can do is register the Spring ConversionService bean and implement the 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); } } 
+4
source

A simple solution that does not require any Java code is to use Spring Expression Language (SpEL) .

(My example uses java.time.Duration, not Joda stuff, but I think you will get it anyway.)

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

Another rather than elegant option is to use the String installer, which calls the parse method.

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

Source: https://habr.com/ru/post/1237116/


All Articles