• Save
Spring has got me under it’s SpEL
Upcoming SlideShare
Loading in...5

Like this? Share it with your network


Spring has got me under it’s SpEL



Springsource new expression language that came out in Spring 3.0

Springsource new expression language that came out in Spring 3.0



Total Views
Views on SlideShare
Embed Views



5 Embeds 132

http://bargateaxis.blogspot.com 61
http://bargateaxis.blogspot.co.il 57
https://bargateaxis.blogspot.com 11
http://bargateaxis.blogspot.co.uk 2
https://twitter.com 1



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
  • 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
    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
    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
    Your message goes here
  • This is a good slide :D
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment
  • 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 Presentation Transcript

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