Published 10 Oct, 2022

Java - Default value as Duration at @Value

Category Java
Modified : Nov 30, 2022
23

I need to specify default value for an instance variable which is of type java.time.Duration

The default value which I pass is being read as String, causing IllegalStateException

My class

public class Test {
  @Value("$")
  private Duration commitInterval;

  .
  .
  .

}

Exception:

  Unsatisfied dependency expressed through field 'commitInterval'; 
  nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.time.Duration'; 
  nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.time.Duration': no matching editors or conversion strategy found

Answers

There are 1 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Java, Spring, Spring Boot. These have been categorized in sections for a clear and precise explanation.

13

You could use SpEL expression directly to invoke factory method of Duration class :

@Value("$}")
private Duration commitInterval;

however as you can see it is a bit verbose. or a bit easier version as OP mentioned in comment :

@Value("$}")
private Duration commitInterval;