Spring Expression Language (SpEL): parse String to int

I have a property ( String , obviously), expressed in minutes, that I want to convert to int before I do some arithmetic and inject it into my Spring bean. Right now I have this SpEL expression:

 #{T(java.lang.Integer).parseInt(myProperties['MIN_TIME']) * 60 * 1000} 

where myProperties is a simple java.util.Properties bean.

Not that I was particularly annoyed by this expression, but nonetheless: Does SpEL have a more beautiful, built-in way to parse strings into numerical values?

Thanks!

+6
source share
2 answers

Not like that, for example. see how developers create them here: https://jira.springsource.org/browse/SPR-8716

A slightly shorter version may be

 #{new Integer(myProperties['MIN_TIME']) * 60 * 1000} 
+9
source

Another way to do this is to use the util namespace to define the properties of the bean, ... XMLNS: Util = "http://www.springframework.org/schema/util" ... http://www.springframework.org/schema / util http://www.springframework.org/schema/util/spring-util-3.1.xsd ...

 <util:properties id="apiProperties" location="classpath:/api.properties" /> 

then use alternative syntax for bean properties

 @Value("#{apiProperties['api.orders.pingFrequency']}") private Integer pingFrequency; 

The spring util bean properties generated by the context will parse and transform before assigning the value.

0
source

Source: https://habr.com/ru/post/915911/


All Articles