Tuesday, January 17, 2012

Use Spring 3 Expression Language (spEL) to get an Integer from an environment variable

Today, I played with Spring Batch. As you probably know, in a classic XML Spring config file, you can use ${my.property} to inject a system property in a bean attribute. That's quite simple.

But, in a JPA item reader (Spring Batch users should understand that), you cannot use this old syntax to inject values in your HQL query (using a parameterValues property). So, I decided to test the fabulously complicated spEL. A wonderful idea...

So, my problem is to get an Integer value from an argument passed to my JVM with something -Dmy.prop=value. Of course, if I don't have any JVM param, I want to have a default value.

Here is the solution :

#{(T(java.lang.Integer).parseInt(systemProperties['process.past.days']?:0))}

So, let's explain it :
  1. #{(systemProperties['process.past.days'])} is required to retrieve a system property called process.past.days
  2. #{(systemProperties['process.past.days']?:0)} is required if you want to set 0 as default value... but... it's horrible... system properties are Strings!!! So, let's parse it.
  3. #{(T(java.lang.Integer).parseInt(...))} is required to convert your String to an Integer
Waoooh! I did it!

My conclusion is that spEL is powerfull but too complicated. How could we maintain that in a few months or years?