45

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?

2
  • is double works? Commented Mar 11, 2017 at 8:52
  • @AmiHollander it fails even for primitive type double Commented Mar 11, 2017 at 8:57

6 Answers 6

84

Try changing the following line

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

to

@Value("#{new Double('${item.priceFactor}')}")
Sign up to request clarification or add additional context in comments.

2 Comments

one million price answer, very rare and not available in many places
Works like a charm on Spring boot 1.5.9
8

This should solve the problem-

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

2 Comments

int is primitive.. Try the object Integer
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.
1

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.

Comments

1

Below logic works for me without using new Double:

@Value("${item.priceFactor}")
private Double priceFactor;

item.priceFactor=0.1

Spring will automatically convert for you.

Comments

0

You forgot the @PropertySource annotation with the name of the properties file as parameter.

It should come before or after your @Service annotation.

Please have a look for a working solution with @Configuration (the super type of @Service) at https://github.com/bojanantonovic/spring-properties-demo.

Comments

-2

How about storing a String and converting to numbers like integers and doubles through getters and setters? For safe code with Java injection you should always use getters and setters and only for other methods in any case. I advice you warmly to read about java security (Which is NOT for hackers), but more for code usage and writing likewise the one you uploaded, wich uses injection.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.