Spring @Value TypeMismatchException:Failed to convert value of type 'java.lang.String' to required type 'java.lang.Double'

43,409

Solution 1

Try changing the following line

@Value("${item.priceFactor}")

to

@Value("#{new Double('${item.priceFactor}')}")

Solution 2

This should solve the problem-

@Value("#{T(Double).parseDouble('${item.priceFactor}')}")
private Double priceFactor;

Solution 3

I had a similar problem but instead of required type 'java.lang.Double' it was required type 'java.lang.Long'. I was using env. variables from a YAML file. Turns out YAML doesn't support the Long data type.

Share:
43,409
guilhebl
Author by

guilhebl

Updated on December 21, 2021

Comments

  • guilhebl
    guilhebl over 2 years

    I want to use the @Value annotation to inject a Double property such as:

    @Service
    public class MyService {
    
        @Value("${item.priceFactor}")
        private Double priceFactor = 0.1;
    
    // ...
    

    and using Spring property placeholder (Properties files):

    item.priceFactor=0.1
    

    I get Exception:

    org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Double'; nested exception is java.lang.NumberFormatException: For input string: "${item.priceFactor}"

    Is there a way to use a Double value coming from a properties file?

  • ArifMustafa
    ArifMustafa about 6 years
    one million price answer, very rare and not available in many places
  • realPK
    realPK about 6 years
    Works like a charm on Spring boot 1.5.9
  • Joe
    Joe about 4 years
    int is primitive.. Try the object Integer
  • alegria
    alegria over 2 years
    I was able to make this work with a primitive Long, and I think this should be a part of the accepted answer since addition of T(Double) instead of Double is the real catch here and hard to be found intuitively. Thank you for this answer.