Your SlideShare is downloading. ×
0
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Spring has got me under it’s SpEL
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Spring has got me under it’s SpEL

8,103

Published on

Springsource new expression language that came out in Spring 3.0

Springsource new expression language that came out in Spring 3.0

Published in: Technology
4 Comments
6 Likes
Statistics
Notes
  • 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?
       Reply 
    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

    Eldad
       Reply 
    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.
    '#{(T(java.lang.Integer).parseInt(eaiJobExecution.getLastWriteableTotalRecords()))+1}'

    Previously the value was
    '#{eaiJobExecution.getLastWriteableTotalRecords()}'

    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.,
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • This is a good slide :D
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
8,103
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
4
Likes
6
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
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 :
  • Transcript

    • 1. Spring has got me under it’s SpEL<br />
    • 2. Short EL introduction<br />Introducing SpEL<br />General Spel Usage<br />Using SpEL<br />Advance usage<br />Elaborate &amp; Q&amp;A<br />Agenda :<br />
    • 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. Introducing SpEL<br />
    • 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. Using SpEL<br />
    • 7. Can be a stand-alone EL parser<br />Fully integrated into to Spring portfolio<br />Has code completion in IntelliJ &amp; Eclipse SpringSource Tool Suite<br />Will be mostly used in XML &amp; Annotations based beans definitions<br />FundemtalsSpEL<br />
    • 8. More Functionality<br />Literal Expressions<br />Boolean, Relational &amp;Ternary operations<br />Regular expressions<br />Accessing Arrays/Maps/Lists<br />Collection projections &amp; selections<br />Templated expressions<br />Full objects access &amp; manipulation<br />And much more…<br />
    • 9. General SpEL usage<br />...Let’s get started,we’ve got a lot to see<br />
    • 10. Configuring beans with SpEL (XML)<br /><ul><li>SpELis incased with some come in handy built in utilities - </li></ul>&lt;bean id=&quot;appConfigurer”class=&quot;com.idi.spel.tests.astro&quot;&gt;<br />&lt;property name=&quot;name” value=&quot;#{systemProperties[‘DB_NAME&apos;]}&quot; /&gt;<br />&lt;/bean&gt;<br />This also works -<br />{#{systemProperties.DB_NAME<br />
    • 11. Configuring beans with SpEL (@Value)<br />@Component<br />public class DataSourceFactory {<br />@Value(&quot;#{systemEnvironment[‘DB_NAME&apos;]}&quot;)<br />private String dbName;<br />// ...<br />}<br />Spring consistency carries on -<br />{#{systemEnvironment.DB_NAME<br />
    • 12. Configuring beans with SpEL (@Value)<br /><ul><li>Accompanying the systemEnvironment &amp; systemProperies there’s SpEL’s built in Date parser </li></ul>@Component<br />public class DataSourceFactory {<br />@Value(&quot;#{’15/12/2010’}&quot;)<br />private Date dbInsertDate; <br />// ...<br />}<br />Major automatic JodaTime support, go on &amp; try it, I haven’t yet<br />
    • 13. More Ready-to-use variables<br /> #{request.getParameter(‘UserId&apos;)}<br /> #{session.getAttribute(‘UserName&apos;)}<br /> will only work in appropriate scoped beans!<br />
    • 14. The Expression Parser <br /><ul><li>The main object used by SpEL internal core
    • 15. Used for raw parsing &amp; complex expression evaluations (we’ll see it in a while)</li></ul>ExpressionParser parser = newSpelExpressionParser();<br />Expression exp = parser.parseExpression(&quot;&apos;Hello World&apos;&quot;);<br />System.out.println(&quot;expression = &quot; + exp.getValue());<br />Expression raw = ((SpelExpressionParser) parser).parseRaw(&quot;1 + 5&quot;);<br />System.out.println(&quot;raw.getValue() = &quot; + raw.getValue());<br />
    • 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. The context sets and holds the #root object, it also gives us ability to override SpEL’s resolvers for constructors &amp; 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</li></ul>EvaluationContext context = new StandardEvaluationContext();<br />context.setVariable(&quot;name&quot;, &quot;J.J Abrams&quot;);<br />parser.parseExpression(&quot;&apos;Producer name : &apos; + #name&quot;).getValue(context, String.class);<br />
    • 19. Constructor invocations<br />parser.parseExpression(“new String[Hi Everybody]”)<br /> #{“new com.idi.astro.basket()”}<br /> #{&quot;new Double(3.0d)“}<br /> #{“new Integer(3.0234457d)”}<br />This works as well as Spring’s internal automatic conversion takes places!<br />
    • 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 &amp; sometimes needed - </li></ul>Map clientsMap = new Hashmap&lt;String,Client&gt;();<br />Clientmoses = new Client(“Moses”,”03-9000111”);<br />clientsMap.put(“Moses”,moses)<br />context.setVariable(“clientsMap&quot;,clientsMap)<br />Expression exp = parser.parseExpression(&quot;#clientsMap[‘Moses’]);<br />Client client = exp.getValue(context, Client.class);<br />client.getPhoneNumber();<br />
    • 21. Setting objects members <br /> #{“Person.Name=‘Bam Bam’“}<br /> #{“Person.Age = 10“}<br /><ul><li>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</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. 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. Relational operations <br /> #{3.0 &lt; 5.0}<br /> #{32 eq 32}<br /> #{‘James’ == ‘James’}<br /> #{‘Apple’ &lt; ‘Orange’}<br /> #{31 gt 22}<br />
    • 26. Ternary, Elvis &amp; the Safe navigation operators<br /><ul><li>We all know &amp; 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</li></ul>Little thumb rule – all the null checking operators start with ?<br />
    • 29. Using the 3 Amigos <br /><ul><li>The ternary </li></ul> #{Client.isActive ? ‘Activated&apos; : ‘Annulled&apos;}<br /><ul><li>The Elvis</li></ul> #{Client.isActive ?: ‘Annulled &apos;}<br /><ul><li>The Safe navigation</li></ul> #{Client.?isActive}<br />
    • 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. instanceof<br /> #{123 instanceof T(Integer)}<br /> #{123L instanceof T(Long)}<br /> #{‘Pirates’ instanceof T(String)}<br /> #{true instanceof T(Boolean)}<br />
    • 32. Regular expressions <br /> #{phoneNumber matches‘d{1,3}-d{3}-d{4}-d{3}&apos;}<br /> #{spel@spring.com matches &apos;[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}&apos;}<br /> #{http://www.springsource.com matches<br />&apos;http://www[a-zA-Z0-9]*(com|edu|net)&apos;}<br />
    • 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. One should supply an implemented ParserContext which contains a prefix &amp; 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</li></li></ul><li>Advance SpEL usage<br />
    • 36. Collection Selection &amp; Projection<br /><ul><li>One of the most interesting &amp; 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.</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&gt;18]}<br />Select the last client who has less the 5 policies<br /> #{Clients.$[Policies&lt;5]&apos;}<br />
    • 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 &gt; 100]}<br />
    • 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&lt;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. 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. Constructors &amp; 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</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 &amp; hard to understand expressions </li></ul>context.registerFunction(“fileCopy&quot;, FileUtils.class.getDeclaredMethod(“copyDirToDir&quot;, new Class[]{String.class,String.class”}));<br />parser.parseExpression(“#fileCopy(‘d:’, ’e:/’)&quot;).getValue(context, Boolean.class);<br />Must be a static method!<br />
    • 44. Security enchantments <br /><ul><li>Using Function &amp; 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&quot;));<br />Expression expr = parser.parseRaw(&quot;name == principal.name&quot;);<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. All good things come to an end… <br /><ul><li>So SpEL has many features and keeps Spring fresh consistent &amp; agile
    • 46. What about performance, let’s say we Collection Project &amp; 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&amp;A anyone???</li>

    ×