0

I have a configuration property:

@ConfigurationProperties(prefix = "x.retention")
@Slf4j
@ConstructorBinding
@AllNonNullByDefault
@Validated
public class RetentionProperties {

  private String isoPeriod;

}

isoPeriod is going to be a period in iso8061 format like P1M -> 1 month duration.

I want to check if the value has a correct format on Configuration Initialisation.

Can I somehow also manipulate the value on initialisation to transform it to Duration? like this

Duration duration = Duration.parse(isoPeriod);

So that I can directly use the Duration value and not validate it later in code?

Diana
  • 935
  • 10
  • 31
  • Spring Boot should automatically convert the value to a `Duration` afaik. See https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToDurationConverter.java (which is used to convert from properties to types during configuration loading). – M. Deinum Apr 12 '23 at 11:25

1 Answers1

0

Just change the type to Duration, Spring Boot will convert it to the proper Duration using the StringToDurationConverter.

Don't make it more complex then that.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
  • Just changing the type doesn't seem to be enough: `java: incompatible types: java.time.Duration cannot be converted to java.lang.String` – Diana Apr 12 '23 at 11:36
  • For binding it is, then you must be using it elsewhere unless you are using some ancient version of Spring Boot that doesn't support this yet. – M. Deinum Apr 12 '23 at 11:40