34
votes

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?

4
is double works?Ami Hollander
@AmiHollander it fails even for primitive type doubleguilhebl

4 Answers

66
votes

Try changing the following line

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

to

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

This should solve the problem-

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

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.

-2
votes

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.