SlideShare a Scribd company logo
1 of 38
Spring has got me under it’s SpEL
Short EL introduction Introducing SpEL General Spel Usage Using SpEL Advance usage Elaborate & Q&A Agenda :
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 -
Introducing SpEL
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
Using SpEL
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 FundemtalsSpEL
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…
General SpEL usage ...Let’s get started,we’ve got a lot to see
Configuring beans with SpEL (XML) ,[object Object],<bean id="appConfigurer”class="com.idi.spel.tests.astro"> <property name="name” value="#{systemProperties[‘DB_NAME']}" /> </bean> This also works - {#{systemProperties.DB_NAME
Configuring beans with SpEL (@Value) @Component public class DataSourceFactory { @Value("#{systemEnvironment[‘DB_NAME']}") private String dbName; // ... } Spring consistency carries on - {#{systemEnvironment.DB_NAME
Configuring beans with SpEL (@Value) ,[object Object],@Component public class DataSourceFactory { @Value("#{’15/12/2010’}") private Date dbInsertDate;  // ... } Major automatic JodaTime support, go on & try it, I haven’t yet
More Ready-to-use variables                   #{request.getParameter(‘UserId')} 		    #{session.getAttribute(‘UserName')}          will only work in appropriate scoped beans!
The Expression Parser  ,[object Object]
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());
More have to know objects ,[object Object]
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
A less common, but useful at times is the ParserContext that provides the behavior of the parser during the lexical stagesEvaluationContext context = new StandardEvaluationContext(); context.setVariable("name", "J.J Abrams"); parser.parseExpression("'Producer name : ' + #name").getValue(context, String.class);
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!
Constructor invocations cont.. ,[object Object],	#{“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) ,[object Object],[object Object],[object Object]
Setting objects members     #{“Person.Name=‘Bam Bam’“}   #{“Person.Age = 10“} ,[object Object]
Using the @Value to set an object member requires a valid target (Field, Method ,Parameter), a compile error helps us there
The valid target can be left unused * * use an empty setter to avoid redundant state variables,[object Object]
We can also mix other SpEL features to build a much more complex String (seen in the examples),[object Object]
Relational operations   #{3.0 < 5.0}  #{32 eq 32}  #{‘James’ == ‘James’}  #{‘Apple’ < ‘Orange’}  #{31 gt 22}
Ternary, Elvis & the Safe navigation operators ,[object Object]
SpEL introduces the long awaited Elvis operator - ?:maybe some day we will have it in the JDK
The Safe Navigation ?. returns null instead of those annoying NPEsLittle thumb rule – all the null checking operators start with ?
Using the 3 Amigos  ,[object Object], #{Client.isActive ? ‘Activated' : ‘Annulled'} ,[object Object], #{Client.isActive ?: ‘Annulled '} ,[object Object], #{Client.?isActive}
The type T Operator  #{T(Math)}  #{T(Math).floor(3.522)}  #{T(String)}  #{T(java.util.Date)}  #{T(Integer).parseInt(‘30’)}
instanceof  #{123 instanceof T(Integer)}  #{123L instanceof T(Long)}  #{‘Pirates’ instanceof T(String)}  #{true instanceof T(Boolean)}
Regular expressions   #{phoneNumber matches‘{1,3}-{3}-{4}-{3}'}  #{spel@spring.com matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+[a-zA-Z]{2,4}'}  #{http://www.springsource.com matches 'http://www.[a-zA-Z0-9]*.(com|edu|net)'}
Expression Templating  ,[object Object]
One should supply an implemented ParserContext  which contains a prefix & a suffix expression
With the @Value there’s no way to pass a  ParserContext, so it leaves use to use the ExpressionParser way for Expression Templating,[object Object]
Collection Selection & Projection ,[object Object]
With merely a few characters one is able to do predicate based selection and projection similar to that in functional programming languages
Magic variables exist that allow the expression access to intermediate stack variables just as you would have in a for loop.,[object Object]

More Related Content

What's hot

Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in javaVishnu Suresh
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFCSunil OS
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An IntroductionSam Brannen
 
ACL in CodeIgniter
ACL in CodeIgniterACL in CodeIgniter
ACL in CodeIgnitermirahman
 
How Hashmap works internally in java
How Hashmap works internally  in javaHow Hashmap works internally  in java
How Hashmap works internally in javaRamakrishna Joshi
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptxvishal choudhary
 
Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design PatternsBobby Bouwmann
 
Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1Mindfire Solutions
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaEdureka!
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAOAnushaNaidu
 

What's hot (20)

Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 
Http session (Java)
Http session (Java)Http session (Java)
Http session (Java)
 
Java collections
Java collectionsJava collections
Java collections
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An Introduction
 
ACL in CodeIgniter
ACL in CodeIgniterACL in CodeIgniter
ACL in CodeIgniter
 
How Hashmap works internally in java
How Hashmap works internally  in javaHow Hashmap works internally  in java
How Hashmap works internally in java
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
 
Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design Patterns
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Array in Java
Array in JavaArray in Java
Array in Java
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
 

Similar to Spring SpEL introduction

FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09Pyxis Technologies
 
Beyond the Style Guides
Beyond the Style GuidesBeyond the Style Guides
Beyond the Style GuidesMosky Liu
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardArchitecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardJAX London
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6Nitay Neeman
 
How Xslate Works
How Xslate WorksHow Xslate Works
How Xslate WorksGoro Fuji
 
Questioning the status quo
Questioning the status quoQuestioning the status quo
Questioning the status quoIvano Pagano
 
Javazone 2010-lift-framework-public
Javazone 2010-lift-framework-publicJavazone 2010-lift-framework-public
Javazone 2010-lift-framework-publicTimothy Perrett
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdflailoesakhan
 
Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesJamund Ferguson
 
Android | Busy Java Developers Guide to Android: UI | Ted Neward
Android | Busy Java Developers Guide to Android: UI | Ted NewardAndroid | Busy Java Developers Guide to Android: UI | Ted Neward
Android | Busy Java Developers Guide to Android: UI | Ted NewardJAX London
 
jQuery Presentation - Refresh Events
jQuery Presentation - Refresh EventsjQuery Presentation - Refresh Events
jQuery Presentation - Refresh EventsEugene Andruszczenko
 
Eugene Andruszczenko: jQuery
Eugene Andruszczenko: jQueryEugene Andruszczenko: jQuery
Eugene Andruszczenko: jQueryRefresh Events
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkDaniel Spector
 
Writing a REST Interconnection Library in Swift
Writing a REST Interconnection Library in SwiftWriting a REST Interconnection Library in Swift
Writing a REST Interconnection Library in SwiftPablo Villar
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsNeil Crookes
 

Similar to Spring SpEL introduction (20)

FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
Beyond the Style Guides
Beyond the Style GuidesBeyond the Style Guides
Beyond the Style Guides
 
JavaScript Needn't Hurt!
JavaScript Needn't Hurt!JavaScript Needn't Hurt!
JavaScript Needn't Hurt!
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardArchitecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
 
How Xslate Works
How Xslate WorksHow Xslate Works
How Xslate Works
 
C to perl binding
C to perl bindingC to perl binding
C to perl binding
 
Questioning the status quo
Questioning the status quoQuestioning the status quo
Questioning the status quo
 
Javazone 2010-lift-framework-public
Javazone 2010-lift-framework-publicJavazone 2010-lift-framework-public
Javazone 2010-lift-framework-public
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
 
Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax Trees
 
Android | Busy Java Developers Guide to Android: UI | Ted Neward
Android | Busy Java Developers Guide to Android: UI | Ted NewardAndroid | Busy Java Developers Guide to Android: UI | Ted Neward
Android | Busy Java Developers Guide to Android: UI | Ted Neward
 
jQuery Presentation - Refresh Events
jQuery Presentation - Refresh EventsjQuery Presentation - Refresh Events
jQuery Presentation - Refresh Events
 
Eugene Andruszczenko: jQuery
Eugene Andruszczenko: jQueryEugene Andruszczenko: jQuery
Eugene Andruszczenko: jQuery
 
Ext Js
Ext JsExt Js
Ext Js
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Writing a REST Interconnection Library in Swift
Writing a REST Interconnection Library in SwiftWriting a REST Interconnection Library in Swift
Writing a REST Interconnection Library in Swift
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIs
 

Recently uploaded

Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 

Recently uploaded (20)

Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 

Spring SpEL introduction

  • 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 -
  • 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
  • 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 FundemtalsSpEL
  • 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.
  • 11. Configuring beans with SpEL (@Value) @Component public class DataSourceFactory { @Value("#{systemEnvironment[‘DB_NAME']}") private String dbName; // ... } Spring consistency carries on - {#{systemEnvironment.DB_NAME
  • 12.
  • 13. More Ready-to-use variables #{request.getParameter(‘UserId')} #{session.getAttribute(‘UserName')} will only work in appropriate scoped beans!
  • 14.
  • 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.
  • 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 stagesEvaluationContext 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.
  • 21.
  • 22. Using the @Value to set an object member requires a valid target (Field, Method ,Parameter), a compile error helps us there
  • 23.
  • 24.
  • 25. Relational operations #{3.0 < 5.0} #{32 eq 32} #{‘James’ == ‘James’} #{‘Apple’ < ‘Orange’} #{31 gt 22}
  • 26.
  • 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 NPEsLittle thumb rule – all the null checking operators start with ?
  • 29.
  • 30. The type T Operator #{T(Math)} #{T(Math).floor(3.522)} #{T(String)} #{T(java.util.Date)} #{T(Integer).parseInt(‘30’)}
  • 31. instanceof #{123 instanceof T(Integer)} #{123L instanceof T(Long)} #{‘Pirates’ instanceof T(String)} #{true instanceof T(Boolean)}
  • 32. Regular expressions #{phoneNumber matches‘{1,3}-{3}-{4}-{3}'} #{spel@spring.com matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+[a-zA-Z]{2,4}'} #{http://www.springsource.com matches 'http://www.[a-zA-Z0-9]*.(com|edu|net)'}
  • 33.
  • 34. One should supply an implemented ParserContext which contains a prefix & a suffix expression
  • 35.
  • 36.
  • 37. With merely a few characters one is able to do predicate based selection and projection similar to that in functional programming languages
  • 38.
  • 39. Collection Projection Select the Clients Policy Nrs #{Clients.![PolicyNr]} This actually is not what the parser expects, and returns a list of Booleanregardless of the expected type Select Clients’ last names #{Clients.![LastName]} Select Clients’ Ages that accedes 100 #{Clients.![Age > 100]}
  • 40.
  • 41.
  • 42. Constructors & methods can be resolved differently if implementing the MethodResolver or ConstructorResolver respectively
  • 43.
  • 44.
  • 45.
  • 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…

Editor's Notes

  1. 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
  2. Example : valueAnnotationParsingTest
  3. Example : arithmeticOperationParsingTest
  4. Example : relationalOperationsParsingTest
  5. Example : TernaryElvisAndSafeNavigationOperations
  6. Example : TOperatorOperations
  7. Example : InstanceOfOpeations
  8. Example : RegularExpressionsOperations
  9. Example : ExpressionTemplatingOperations
  10. Example : CollectionSelectionOperations
  11. Example : CollectionProjectionsOperations
  12. Example : CollectionProjectionsOperations
  13. Example :
  14. Example :
  15. Example : ScenariosForSpringSecurity
  16. Example :