Spring has got me under it’s SpEL


Published on

Springsource new expression language that came out in Spring 3.0

Published in: Technology
  • Hi @ROBALCATARA, just got the changes in 3.2.2 to work,
    and there's some, not as much as I first thought...
    Anyhows, you're question is pretty vague, can you post more info?
    Are you sure you want to  Yes  No
    Your message goes here
  • Hi Robinson, (or Francis your first name?)
    well you made me come back to my SpEL old project,
    and I like to stay up to date with Spring's changes, so naturally I've upgraded all my versions to 3.2.2...and guess what - Runtime errors all over the place :)

    But no problems, it's just a little challenge to fix my code and to see it all work again, I will get back to you with an answer ASAP.

    cheers & 10x

    Are you sure you want to  Yes  No
    Your message goes here
  • Hi Eldad Dor, May I ask you a question. I am trying to use statement in the configuration file.

    Previously the value was

    I want to add 1 to the value returned by eaiJobExecution.getLastWriteableTotalRecords() . But eaiJobExecution.getLastWriteableTotalRecords() is in String. SO I tried to cast it Integer and then increment it by 1. But the result is ZEro. Please help. I will supply more information if my request is vague. Thank you.,
    Are you sure you want to  Yes  No
    Your message goes here
  • This is a good slide :D
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Original SPEL – Simplest Possible Expression Language used for JSP and JSTL (Java pages Standard Tag library) replaced by the Unified EL created for JSP 2.0 and JCF
  • Example : valueAnnotationParsingTest
  • Example : arithmeticOperationParsingTest
  • Example : relationalOperationsParsingTest
  • Example : TernaryElvisAndSafeNavigationOperations
  • Example : TOperatorOperations
  • Example : InstanceOfOpeations
  • Example : RegularExpressionsOperations
  • Example : ExpressionTemplatingOperations
  • Example : CollectionSelectionOperations
  • Example : CollectionProjectionsOperations
  • Example : CollectionProjectionsOperations
  • Example :
  • Example :
  • Example : ScenariosForSpringSecurity
  • Example :
  • Spring has got me under it’s SpEL

    1. 1. Spring has got me under it’s SpEL<br />
    2. 2. Short EL introduction<br />Introducing SpEL<br />General Spel Usage<br />Using SpEL<br />Advance usage<br />Elaborate & Q&A<br />Agenda :<br />
    3. 3. Many EL out there Jboss-EL, MvEL, Unified-EL<br />Giving Java the Dynamic-Typing power it requiresmuch like Groovy and Ruby<br />Some EL’s are pretty powerful, most require to learn a new language entirely, but the convention is much the same, so learning one will provide tools to basically understand them all<br />Expression Languages -<br />
    4. 4. Introducing SpEL<br />
    5. 5. Spring 3.0 biggest new featureoriginal conceived in Spring.Net (don’t mistake it with the original SPEL)<br />Works with all Spring’s portfolio <br />Succinctly express complex concepts<br />Can be used to wire bean properties<br />Has many strong capabilities (but with cost!)<br />Can be used outside of Spring<br />What it SpEL<br />
    6. 6. Using SpEL<br />
    7. 7. Can be a stand-alone EL parser<br />Fully integrated into to Spring portfolio<br />Has code completion in IntelliJ & Eclipse SpringSource Tool Suite<br />Will be mostly used in XML & Annotations based beans definitions<br />FundemtalsSpEL<br />
    8. 8. More Functionality<br />Literal Expressions<br />Boolean, Relational &Ternary operations<br />Regular expressions<br />Accessing Arrays/Maps/Lists<br />Collection projections & selections<br />Templated expressions<br />Full objects access & manipulation<br />And much more…<br />
    9. 9. General SpEL usage<br />...Let’s get started,we’ve got a lot to see<br />
    10. 10. Configuring beans with SpEL (XML)<br /><ul><li>SpELis incased with some come in handy built in utilities - </li></ul><bean id="appConfigurer”class="com.idi.spel.tests.astro"><br /><property name="name” value="#{systemProperties[‘DB_NAME']}" /><br /></bean><br />This also works -<br />{#{systemProperties.DB_NAME<br />
    11. 11. Configuring beans with SpEL (@Value)<br />@Component<br />public class DataSourceFactory {<br />@Value("#{systemEnvironment[‘DB_NAME']}")<br />private String dbName;<br />// ...<br />}<br />Spring consistency carries on -<br />{#{systemEnvironment.DB_NAME<br />
    12. 12. Configuring beans with SpEL (@Value)<br /><ul><li>Accompanying the systemEnvironment & systemProperies there’s SpEL’s built in Date parser </li></ul>@Component<br />public class DataSourceFactory {<br />@Value("#{’15/12/2010’}")<br />private Date dbInsertDate; <br />// ...<br />}<br />Major automatic JodaTime support, go on & try it, I haven’t yet<br />
    13. 13. More Ready-to-use variables<br /> #{request.getParameter(‘UserId')}<br /> #{session.getAttribute(‘UserName')}<br /> will only work in appropriate scoped beans!<br />
    14. 14. The Expression Parser <br /><ul><li>The main object used by SpEL internal core
    15. 15. Used for raw parsing & complex expression evaluations (we’ll see it in a while)</li></ul>ExpressionParser parser = newSpelExpressionParser();<br />Expression exp = parser.parseExpression("'Hello World'");<br />System.out.println("expression = " + exp.getValue());<br />Expression raw = ((SpelExpressionParser) parser).parseRaw("1 + 5");<br />System.out.println("raw.getValue() = " + raw.getValue());<br />
    16. 16. More have to know objects<br /><ul><li>A side from the ExpressionParser, there’s the EvaluationContext , which lives as a part of the expression created, or as the expression itself altogether
    17. 17. The context sets and holds the #root object, it also gives us ability to override SpEL’s resolvers for constructors & methods, and even has operatorOverloding capabilities
    18. 18. A less common, but useful at times is the ParserContext that provides the behavior of the parser during the lexical stages</li></ul>EvaluationContext context = new StandardEvaluationContext();<br />context.setVariable("name", "J.J Abrams");<br />parser.parseExpression("'Producer name : ' + #name").getValue(context, String.class);<br />
    19. 19. Constructor invocations<br />parser.parseExpression(“new String[Hi Everybody]”)<br /> #{“new com.idi.astro.basket()”}<br /> #{"new Double(3.0d)“}<br /> #{“new Integer(3.0234457d)”}<br />This works as well as Spring’s internal automatic conversion takes places!<br />
    20. 20. Constructor invocations cont..<br /><ul><li>SpEL can do more…</li></ul> #{“new Window(‘Policy renewal’).windowName()”}<br />Window window = (Window) parser.parseExpression(“new Window(‘Policy renewal’”).getValue()<br /> Use the desiredResultType to avoid casting – <br />Window window=parser.parseExpression(“new Window()”) .getValue(Window.class)<br /><ul><li>SpEL is pretty amazing, but it’s really a lexical parser, not a DI framework by it self, so use it wisely and avoid constructing objects if not required!</li></li></ul><li>Access objects members <br /> #{“Person.Name“}<br /> #{“Person.name“}<br /> #{“Person.getName()“}<br /><ul><li>More cool stuff can be done (seen in many of the examples) , but remember this :Use it, don’t Abuse it! </li></li></ul><li>Access objects cont<br /><ul><li>Accessing collections is mostly used with collection selection, we’ll get to that later, but simple map access is pretty straight forward & sometimes needed - </li></ul>Map clientsMap = new Hashmap<String,Client>();<br />Clientmoses = new Client(“Moses”,”03-9000111”);<br />clientsMap.put(“Moses”,moses)<br />context.setVariable(“clientsMap",clientsMap)<br />Expression exp = parser.parseExpression("#clientsMap[‘Moses’]);<br />Client client = exp.getValue(context, Client.class);<br />client.getPhoneNumber();<br />
    21. 21. Setting objects members <br /> #{“Person.Name=‘Bam Bam’“}<br /> #{“Person.Age = 10“}<br /><ul><li>Access an object member is self explanatory
    22. 22. Using the @Value to set an object member requires a valid target (Field, Method ,Parameter), a compile error helps us there
    23. 23. The valid target can be left unused * * use an empty setter to avoid redundant state variables</li></li></ul><li>Mixing text with property access<br /> #{“My name is +Person.Name“}<br /><ul><li>When mixing text with properties from other beans, need to remember that the beans are all defined and initialized in the same context!
    24. 24. We can also mix other SpEL features to build a much more complex String (seen in the examples)</li></li></ul><li>Arithmetic operations <br /> #{3.0f + 5.0f}<br /> #{32 ^ 5}<br /> #{‘James’ + ‘ ‘ + ‘Bond’}<br /> #{5.0d % 3.1d}<br /> #{3.0f div 5.0f}<br /> #{3L * 50L}<br />
    25. 25. Relational operations <br /> #{3.0 < 5.0}<br /> #{32 eq 32}<br /> #{‘James’ == ‘James’}<br /> #{‘Apple’ < ‘Orange’}<br /> #{31 gt 22}<br />
    26. 26. Ternary, Elvis & the Safe navigation operators<br /><ul><li>We all know & love the ternary operator, which inline our logical expressions. (forget how to use it, let IntelliJ do the work  )
    27. 27. SpEL introduces the long awaited Elvis operator - ?:maybe some day we will have it in the JDK
    28. 28. The Safe Navigation ?. returns null instead of those annoying NPEs</li></ul>Little thumb rule – all the null checking operators start with ?<br />
    29. 29. Using the 3 Amigos <br /><ul><li>The ternary </li></ul> #{Client.isActive ? ‘Activated' : ‘Annulled'}<br /><ul><li>The Elvis</li></ul> #{Client.isActive ?: ‘Annulled '}<br /><ul><li>The Safe navigation</li></ul> #{Client.?isActive}<br />
    30. 30. The type T Operator<br /> #{T(Math)}<br /> #{T(Math).floor(3.522)}<br /> #{T(String)}<br /> #{T(java.util.Date)}<br /> #{T(Integer).parseInt(‘30’)}<br />
    31. 31. instanceof<br /> #{123 instanceof T(Integer)}<br /> #{123L instanceof T(Long)}<br /> #{‘Pirates’ instanceof T(String)}<br /> #{true instanceof T(Boolean)}<br />
    32. 32. Regular expressions <br /> #{phoneNumber matches‘d{1,3}-d{3}-d{4}-d{3}'}<br /> #{spel@spring.com matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}'}<br /> #{http://www.springsource.com matches<br />'http://www[a-zA-Z0-9]*(com|edu|net)'}<br />
    33. 33. Expression Templating <br /><ul><li>SpEL provides a some what unnecessary String Templating feature, (maybe could be useful in a large expression rule engines…)
    34. 34. One should supply an implemented ParserContext which contains a prefix & a suffix expression
    35. 35. With the @Value there’s no way to pass a ParserContext, so it leaves use to use the ExpressionParser way for Expression Templating</li></li></ul><li>Advance SpEL usage<br />
    36. 36. Collection Selection & Projection<br /><ul><li>One of the most interesting & cool features in SpEL
    37. 37. With merely a few characters one is able to do predicate based selection and projection similar to that in functional programming languages
    38. 38. Magic variables exist that allow the expression access to intermediate stack variables just as you would have in a for loop.</li></li></ul><li>Collection Selection<br />Select all Clients that name start with B<br /> #{Clients.?[Name.startsWith(‘B’)]}<br />Select the first client who’s over 18 years in age<br /> #{Clients.^[Age>18]}<br />Select the last client who has less the 5 policies<br /> #{Clients.$[Policies<5]'}<br />
    39. 39. Collection Projection<br />Select the Clients Policy Nrs<br /> #{Clients.![PolicyNr]}<br />This actually is not what the parser expects, and returns a list of Booleanregardless of the expected type<br />Select Clients’ last names<br /> #{Clients.![LastName]}<br />Select Clients’ Ages that accedes 100<br /> #{Clients.![Age > 100]}<br />
    40. 40. Collection Project then Select<br /><ul><li>Projection on most occasions will be used along side collection selection</li></ul>Select the Policy Nrs which accedes given number<br /> #{Clients.![PolicyNr].?[#this<100000)]}<br />The useful #this feature comes in handy <br />Select Clients’ last names that end with ‘Cohen’<br /> #{Clients.![LastName].?[#this.endsWith(‘Cohen’)]}<br />
    41. 41. State and behavior registration<br /><ul><li>The evaluation context can be provided with state or behavior to take into account during the parsing stage
    42. 42. Constructors & methods can be resolved differently if implementing the MethodResolver or ConstructorResolver respectively
    43. 43. The Resolvers can be provided with executors, a really cool execution displacement which has great power in aspect programming</li></li></ul><li>Adding custom functions<br />Only available with programming SpEL<br /><ul><li>SpEL provides registering methods to be used, say you want to incorporate your business logic to avoid complicated expressions or to shorten long & hard to understand expressions </li></ul>context.registerFunction(“fileCopy", FileUtils.class.getDeclaredMethod(“copyDirToDir", new Class[]{String.class,String.class”}));<br />parser.parseExpression(“#fileCopy(‘d:’, ’e:/’)").getValue(context, Boolean.class);<br />Must be a static method!<br />
    44. 44. Security enchantments <br /><ul><li>Using Function & Property registration to secure an application is not that complicated and can provide another way when designing a security model</li></ul>ctx.addPropertyAccessor(newSecurityPrincipalAccessor());<br />ctx.setRootObject(newPerson(“Mike"));<br />Expression expr = parser.parseRaw("name == principal.name");<br />value = expr.getValue(ctx, Boolean.class);<br />The object has an inner class holding a name property <br />We initialize the Person class, providing a name<br />Raw parsing the expression – validating the Person’s name to the Principal’s name<br />
    45. 45. All good things come to an end… <br /><ul><li>So SpEL has many features and keeps Spring fresh consistent & agile
    46. 46. What about performance, let’s say we Collection Project & Select using SpEL a large list of objects, will it be more efficient with SpEL or do it in the good old java way?
    47. 47. Well, naturally, parsing takes time, and building the lexical model is not that cheap, so using SpEL will have a cost in performance, but still…
    48. 48. Q&A anyone???</li>