Spring has always been an interesting framework to work with, the simplicity to choose and use any of its features has been strong reason behind its popularity and adoptability in many architectures. Whats more, the features which Spring has been providing all these years, have always helped organisations to build loosly coupled architecture (yeah, offcourse its true only if someone dont mess with it.)
Recently while working on one of the project I came across one more interesting feature of Spring – Expression Language (Henceforth referred as Spring EL). Anyone who is interested in implementing Expression feature in project, must have a look at this new feature of Spring. There are other libraries available like OGNL, MVEL etc but I liked the simplicity and extendability provided by Spring EL.
Since Spring EL documentation is enough to get started, I would like to directly jump into one of the adavanced features of Spring EL. I couldnt find any documenation on this and hence thought of putting my findings here. The feature is nothing but extendability provided by Spring EL to resolve object properties while evaluating expression.
Consider following example
ExpressionParser parser = new SpelExpressionParser(); Organisation org = ..//Oragnisation is value object, having employee as type of List
StandardEvaluationContext expContext = new StandardEvaluationContext(org); //Context initialization code goes here like registering custom expression function //... Expression exp = parser.parseExpression("1+2*3*(#count(employee.departments))"); Integer value = (Integer)exp.getValue(expContext, Integer.class);
In above scenario, I want to count the number of departments assigned to each employee stored in “Organisation” object and do some mathematical operations on it. While count function (remember “count” is not built-in function, you need to write implementation for this) does the job of counting the number of elements, invoking “departments” on employee object would result into an error. Spring by default would like to search for “departments” property on List
You need to implement this interface and can get total control over how Spring EL accesses object properties. To provide you more clue about how to develop your own PropertyAccessor, have a look at the default PropertyAccessor implementation provided by Spring EL –
There are quite few other features like method resolver, bean resolver etc worth exploring and they are really helpful if one wants to customize Expression evaluation as per need.