Passing int to spring property

I want to pass int instead of the string , which is used by default in spring PropertyPlaceholderConfigurer .

<property name="mailServerPort" value="${mail.port}" /> 

This gives me an error because mailServerPort is an int type and $ {mail.port} is a string type.

How can I convert $ {mail.port} to int?

+6
source share
4 answers

Spring handles the conversion based on the target type, if possible.

Are you sure you installed

 mail.port 

value with int?

+7
source

According to me, casting should work correctly if the port value is a valid integer.

However, if you encounter a problem, you can try SpringExpressionLanguage (SpEL) to convert.

 <property name="mailServerPort" value="#{ T(java.lang.Integer).parseInt(mail.port) }"/> 

Hope this helps you.

+9
source

Spring should handle it automatically, although if it gives an error, you can use the type attribute's property tag and specify and indicate the type of request. For example

 <property name="mailServerPort" type="int" value="${mail.port}" /> 

Hope this helps .. :-)

0
source

All of the above answers will work fine if a property value is provided. If it is empty, you can use SpringExpressionLanguage to handle this case and specify a default value:

 <property name="mailServerPort" value="#{ '${mail.port}'.isEmpty() ? '8080' : '${mail.port}' }"/> 
0
source

All Articles