@Value annotation type casting to Integer from String

annotations, casting, java, property-placeholder, spring

Solution

Assuming you have a properties file on your classpath that contains

api.orders.pingFrequency=4

I tried inside a `@Controller`

@Controller
public class MyController {     
    @Value("${api.orders.pingFrequency}")
    private Integer pingFrequency;
    ...
}

With my servlet context containing :

<context:property-placeholder location="classpath:myprops.properties" />

It worked perfectly.

So either your property is not an integer type, you don't have the property placeholder configured correctly, or you are using the wrong property key.

I tried running with an invalid property value, `4123;`. The exception I got is

java.lang.NumberFormatException: For input string: "4123;"

which makes me think the value of your property is

api.orders.pingFrequency=(java.lang.Integer)${api.orders.pingFrequency}

Problem

I'm trying to cast the output of a value to an integer: ``` @Value("${api.orders.pingFrequency}") private Integer pingFrequency; ``` The above throws the error ``` org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "(java.lang.Integer)${api.orders.pingFrequency}" ``` I've also tried `@Value("(java.lang.Integer)${api.orders.pingFrequency}")` Google doesn't appear to say much on the subject. I'd like to always be dealing with an integer instead of having to parse this value everywhere it's used. Workaround I realize a workaround may be to use a setter method to run the conversion for me, but if Spring can do it I'd rather learn something about Spring.

Original source