SlideShare une entreprise Scribd logo
1  sur  35
Télécharger pour lire hors ligne
Spring Framework - Expression Language




                SPRING FRAMEWORK 3.0
Dmitry Noskov   Spring Expression Language
What is SpEL?
   is a powerful expression language
   much like OGNL, Jboss EL, etc.
   supports querying and manipulating an object
    graph at runtime
   can be used across all the products in the Spring
    portfolio
   can be used outside of Spring



                 Spring Framework - Expression Language   Dmitry Noskov
Features
   expressions
   accessing properties, arrays, etc.
   assignment
   method invocation
   collection selection & projection
   etc.




                  Spring Framework - Expression Language   Dmitry Noskov
Fundamentals
   ExpressionParser
   Expression
     getValue
     setValue

   EvaluationContext
     root
     setVariable

     propertyAccessor



                 Spring Framework - Expression Language   Dmitry Noskov
Expression access
   configuration XML / @Value
       #{expression}
   programming
     parser.parseExpression(“expression for root”)
     parser.parseExpression(“#expression for variable”)

   custom template
       parser.parseExpression(“it is #{expression}”)



                    Spring Framework - Expression Language   Dmitry Noskov
Using SpEL




      Spring Framework - Expression Language   Dmitry Noskov
XML

<bean id="systemConfig" class="org.training.spel.SystemConfig">
  <property name="operatingSystem"
            value="#{systemProperties['os.name']}"/>


  <property name="javaVersion"
            value="#{systemProperties['java.vm.version']}"/>
</bean>




                  Spring Framework - Expression Language   Dmitry Noskov
@Value

public class SystemConfig {


    @Value("#{systemProperties['java.vm.version']}")
    private String operatingSystem;


    @Value("#{systemProperties['java.vm.version']}")
    private String javaVersion;


}



Note: <context:annotation-config/>


                    Spring Framework - Expression Language   Dmitry Noskov
Expressions




      Spring Framework - Expression Language   Dmitry Noskov
Literal expressions
ExpressionParser parser = new SpelExpressionParser();


parser.parseExpression("'Hello World'").getValue(String.class);


parser.parseExpression("6.0221415E+23").getValue(Double.class);


parser.parseExpression("0x7FFFFFFF").getValue(Integer.class);


parser.parseExpression("'2011/01/17'").getValue(Date.class);


parser.parseExpression("true").getValue();


parser.parseExpression("null").getValue();


                  Spring Framework - Expression Language   Dmitry Noskov
Type conversion
   Converter
    public interface Converter<S, T> {
        T convert(S source);
    }

   ConversionService


   http://static.springsource.org/spring/docs/3.0.x/spri
    ng-framework-reference/html/validation.html#core-
    convert

                     Spring Framework - Expression Language   Dmitry Noskov
Object properties

   #{person.name}

   #{person.Name}

   #{person.getName()}




                Spring Framework - Expression Language   Dmitry Noskov
Collections

   #{list[0]}
   #{list[0].name}

   #{map[‘key’]}




                 Spring Framework - Expression Language   Dmitry Noskov
Methods

   #{‘Some Text’.substring(0, 2)}

   #{‘Some Text’.startsWith(‘text’)}

   #{“variable.toString()”}




                  Spring Framework - Expression Language   Dmitry Noskov
Relational operators

   #{5 == 5} or #{5 eq 5}
   #{‘black’ > ’block’} or #{‘black’ gt ‘block’}

   #{‘text’ instanceof T(int)}
   #{'5.00' matches '^-?d+(.d{2})?$'}




                  Spring Framework - Expression Language   Dmitry Noskov
Arithmetic operators

   #{5 + 5}
   #{(5 + 5) * 2}
   #{17 / 5 % 3}

   #{‘Hello’ + ‘ ‘ + ‘world’}




                  Spring Framework - Expression Language   Dmitry Noskov
Logical operators

   #{true or false}

   #{!true}

   #{not isUserInGroup(‘admin’)}




                 Spring Framework - Expression Language   Dmitry Noskov
Assignment

SimpleBean dima = new SimpleBean("Dima", 26);
EvaluationContext context = new StandardEvaluationContext(dima);


parser.parseExpression("name").setValue(context, "Dmitry");


parser.parseExpression("age=27").getValue(context);




                  Spring Framework - Expression Language   Dmitry Noskov
Type operator
   #{T(java.util.Date)}
   #{T(String)}
   #{T(int)}

   accessing static class members
     #{T(Math).PI}
     #{T(Math).random()}




                  Spring Framework - Expression Language   Dmitry Noskov
instanceof
   #{‘text’ instanceof T(String)}

   #{27 instanceof T(Integer)}

   #{false instanceof T(Boolean)}




                  Spring Framework - Expression Language   Dmitry Noskov
Constructor

   #{new org.training.spel.Person(‘Misha’, 28)}

   #{list.add(new org.training.spel.Person())}




                  Spring Framework - Expression Language   Dmitry Noskov
Variable registration

Map<String, Person> map = new HashMap<String, Person>();
map.put("Dima", new Person("Dima", 27));
map.put("Anya", new Person("Anya", 23));


ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable("map", map);
ctx.setVariable("anya", "Anya");


parser.parseExpression("#map['Dima']").getValue(ctx);
parser.parseExpression("#map[#anya]").getValue(ctx);



                  Spring Framework - Expression Language   Dmitry Noskov
If-then-else

   #{person.age>50 ? ‘Old’ : ‘Young’}

   #{person.name ? : ‘N/A’}




                Spring Framework - Expression Language   Dmitry Noskov
Safe navigation

   #{address.city?.name}



   #{person.name?.length()}




                Spring Framework - Expression Language   Dmitry Noskov
Collection selection
   select all
     #{list.?[age>20]}
     #{list.?[name.startsWith(‘D’)]}

   select first
       #{list.^[age>20]}
   select last
       #{list.$[getAge()>20]}



                    Spring Framework - Expression Language   Dmitry Noskov
Collection projection
   select the names of all elements
       #{list.![name]}
   select the names length of all elements
       #{list.![name.length()]}




                     Spring Framework - Expression Language   Dmitry Noskov
Functions

ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext();


context.registerFunction("max", Collections.class.
   getDeclaredMethod("max", new Class[]{Collection.class}));



parser.parseExpression("#max(#list.![age])").getValue(context);




                  Spring Framework - Expression Language   Dmitry Noskov
Templating
ExpressionParser parser = new SpelExpressionParser();


String value = parser.parseExpression(
       "Random number is #{T(java.lang.Math).random()}",
       new TemplateParserContext()
).getValue(String.class);



But:
parser.parseExpression("#{#primes.?[#this>10]}", …)




                  Spring Framework - Expression Language   Dmitry Noskov
#root and #this

   array of integer
list.addAll(Arrays.asList(2,3,5,7,11,13,17));
p.parseExpression("#list.?[#this>10]").getValue(context);




   list of age
List<Person> list = new ArrayList<Person>();
p.parseExpression("#list.![age].?[#this>20]").getValue(context);




                  Spring Framework - Expression Language   Dmitry Noskov
Using root object
   unchanging
    StandardEvaluationContext context = new
                 StandardEvaluationContext(new Person("Dima", 25));
    parser.parseExpression("name").getValue(context);

   changing
    parser.parseExpression("name").getValue(new Person("Dima", 27));

   cached context
    StandardEvaluationContext context = new
                 StandardEvaluationContext(new Person("Dima", 25));
    parser.parseExpression("name").getValue(context, person1);
    parser.parseExpression("name").getValue(context, person2);


                    Spring Framework - Expression Language   Dmitry Noskov
Access to Spring context
<bean id="simpleBean" class="org.training.spel.Person"
     p:name="Misha" p:age="#{25+23}"/>


ApplicationContext context =
               new ClassPathXmlApplicationContext("context.xml");
Person bean = context.getBean(Person.class);


ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext evaluation =
                             new StandardEvaluationContext(context);
evaluation.addPropertyAccessor(new BeanFactoryAccessor());


parser.parseExpression("simpleBean").getValue(evaluation);


                  Spring Framework - Expression Language   Dmitry Noskov
Wiring properties
   simple
    @Value("#{systemProperties['locale']}")
    private Locale locale;

   default
    @Value("#{systemProperties['locale']?:'RU'}")
    private Locale locale;

   selective
    @Value("#{systemProperties['level']>2 ? gold : default}")
    private AccountRepository repository;




                    Spring Framework - Expression Language   Dmitry Noskov
Information
   Spring type conversion reference
    http://static.springsource.org/spring/docs/3.0.x/spring-
    framework-reference/html/validation.html#core-convert
   Spring EL reference
    http://static.springsource.org/spring/docs/3.0.x/spring-
    framework-reference/html/expressions.html




                  Spring Framework - Expression Language   Dmitry Noskov
Questions




            Spring Framework - Expression Language   Dmitry Noskov
The end




             http://www.linkedin.com/in/noskovd

      http://www.slideshare.net/analizator/presentations

Contenu connexe

Tendances

Tendances (20)

Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
Spring boot
Spring bootSpring boot
Spring boot
 
Intro to vue.js
Intro to vue.jsIntro to vue.js
Intro to vue.js
 
Java script Basic
Java script BasicJava script Basic
Java script Basic
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Express js
Express jsExpress js
Express js
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 
JAVASCRIPT PPT [Autosaved].pptx
JAVASCRIPT PPT [Autosaved].pptxJAVASCRIPT PPT [Autosaved].pptx
JAVASCRIPT PPT [Autosaved].pptx
 
Why Vue.js?
Why Vue.js?Why Vue.js?
Why Vue.js?
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Expressjs
ExpressjsExpressjs
Expressjs
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Express JS
Express JSExpress JS
Express JS
 
Rest API with Swagger and NodeJS
Rest API with Swagger and NodeJSRest API with Swagger and NodeJS
Rest API with Swagger and NodeJS
 

En vedette

Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - ValidationDzmitry Naskou
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data AccessDzmitry Naskou
 
Spring Framework - Web Flow
Spring Framework - Web FlowSpring Framework - Web Flow
Spring Framework - Web FlowDzmitry Naskou
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring SecurityDzmitry Naskou
 
Spring has got me under it’s SpEL
Spring has got me under it’s SpELSpring has got me under it’s SpEL
Spring has got me under it’s SpELEldad Dor
 
Banco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase LiteBanco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase LiteFernando Camargo
 
Boas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful APIBoas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful APIFernando Camargo
 
Construção de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em JavaConstrução de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em JavaFernando Camargo
 
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf Conference
 
Профессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseПрофессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseAlexander Granin
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникOrm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникAlina Dolgikh
 
JoinCommunity 2 - Projetando um novo app usando user centered design
JoinCommunity 2 - Projetando um novo app usando user centered designJoinCommunity 2 - Projetando um novo app usando user centered design
JoinCommunity 2 - Projetando um novo app usando user centered designFernando Camargo
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionEr. Gaurav Kumar
 
How to write a well-behaved Python command line application
How to write a well-behaved Python command line applicationHow to write a well-behaved Python command line application
How to write a well-behaved Python command line applicationgjcross
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate TutorialRam132
 
GNU Parallel - Ole Tange
GNU Parallel - Ole TangeGNU Parallel - Ole Tange
GNU Parallel - Ole TangeFSCONS
 

En vedette (20)

Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - Validation
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
 
Spring Framework - Web Flow
Spring Framework - Web FlowSpring Framework - Web Flow
Spring Framework - Web Flow
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 
Spring has got me under it’s SpEL
Spring has got me under it’s SpELSpring has got me under it’s SpEL
Spring has got me under it’s SpEL
 
Banco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase LiteBanco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase Lite
 
Boas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful APIBoas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful API
 
Construção de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em JavaConstrução de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em Java
 
Design de RESTful APIs
Design de RESTful APIsDesign de RESTful APIs
Design de RESTful APIs
 
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
 
Профессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseПрофессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом Enterprise
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникOrm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел Вейник
 
JoinCommunity 2 - Projetando um novo app usando user centered design
JoinCommunity 2 - Projetando um novo app usando user centered designJoinCommunity 2 - Projetando um novo app usando user centered design
JoinCommunity 2 - Projetando um novo app usando user centered design
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic Introduction
 
How to write a well-behaved Python command line application
How to write a well-behaved Python command line applicationHow to write a well-behaved Python command line application
How to write a well-behaved Python command line application
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
GNU Parallel - Ole Tange
GNU Parallel - Ole TangeGNU Parallel - Ole Tange
GNU Parallel - Ole Tange
 
Hibernate
HibernateHibernate
Hibernate
 

Similaire à Spring Framework Expression Language Guide

C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607Kevin Hazzard
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Oliver Gierke
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)HamletDRC
 
Twitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian NetworkTwitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian NetworkHendy Irawan
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
 
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with EclipseEclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with EclipseHeiko Behrens
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - StockholmJan Kronquist
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 
Elasticsearch And Apache Lucene For Apache Spark And MLlib
Elasticsearch And Apache Lucene For Apache Spark And MLlibElasticsearch And Apache Lucene For Apache Spark And MLlib
Elasticsearch And Apache Lucene For Apache Spark And MLlibJen Aman
 
2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factors2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factorskrishna singh
 
Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Guy Lebanon
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
Ruby 1.9.3 Basic Introduction
Ruby 1.9.3 Basic IntroductionRuby 1.9.3 Basic Introduction
Ruby 1.9.3 Basic IntroductionPrabu D
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022
Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022
Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022InfluxData
 

Similaire à Spring Framework Expression Language Guide (20)

360|iDev
360|iDev360|iDev
360|iDev
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Play á la Rails
Play á la RailsPlay á la Rails
Play á la Rails
 
The Rust Borrow Checker
The Rust Borrow CheckerThe Rust Borrow Checker
The Rust Borrow Checker
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Twitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian NetworkTwitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian Network
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with EclipseEclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Elasticsearch And Apache Lucene For Apache Spark And MLlib
Elasticsearch And Apache Lucene For Apache Spark And MLlibElasticsearch And Apache Lucene For Apache Spark And MLlib
Elasticsearch And Apache Lucene For Apache Spark And MLlib
 
2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factors2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factors
 
Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Data Analysis with R (combined slides)
Data Analysis with R (combined slides)
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Ruby 1.9.3 Basic Introduction
Ruby 1.9.3 Basic IntroductionRuby 1.9.3 Basic Introduction
Ruby 1.9.3 Basic Introduction
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022
Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022
Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022
 

Dernier

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
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
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
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"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
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"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
 
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
 
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
 

Dernier (20)

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
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
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
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"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...
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 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
 
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
 
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!
 

Spring Framework Expression Language Guide

  • 1. Spring Framework - Expression Language SPRING FRAMEWORK 3.0 Dmitry Noskov Spring Expression Language
  • 2. What is SpEL?  is a powerful expression language  much like OGNL, Jboss EL, etc.  supports querying and manipulating an object graph at runtime  can be used across all the products in the Spring portfolio  can be used outside of Spring Spring Framework - Expression Language Dmitry Noskov
  • 3. Features  expressions  accessing properties, arrays, etc.  assignment  method invocation  collection selection & projection  etc. Spring Framework - Expression Language Dmitry Noskov
  • 4. Fundamentals  ExpressionParser  Expression  getValue  setValue  EvaluationContext  root  setVariable  propertyAccessor Spring Framework - Expression Language Dmitry Noskov
  • 5. Expression access  configuration XML / @Value  #{expression}  programming  parser.parseExpression(“expression for root”)  parser.parseExpression(“#expression for variable”)  custom template  parser.parseExpression(“it is #{expression}”) Spring Framework - Expression Language Dmitry Noskov
  • 6. Using SpEL Spring Framework - Expression Language Dmitry Noskov
  • 7. XML <bean id="systemConfig" class="org.training.spel.SystemConfig"> <property name="operatingSystem" value="#{systemProperties['os.name']}"/> <property name="javaVersion" value="#{systemProperties['java.vm.version']}"/> </bean> Spring Framework - Expression Language Dmitry Noskov
  • 8. @Value public class SystemConfig { @Value("#{systemProperties['java.vm.version']}") private String operatingSystem; @Value("#{systemProperties['java.vm.version']}") private String javaVersion; } Note: <context:annotation-config/> Spring Framework - Expression Language Dmitry Noskov
  • 9. Expressions Spring Framework - Expression Language Dmitry Noskov
  • 10. Literal expressions ExpressionParser parser = new SpelExpressionParser(); parser.parseExpression("'Hello World'").getValue(String.class); parser.parseExpression("6.0221415E+23").getValue(Double.class); parser.parseExpression("0x7FFFFFFF").getValue(Integer.class); parser.parseExpression("'2011/01/17'").getValue(Date.class); parser.parseExpression("true").getValue(); parser.parseExpression("null").getValue(); Spring Framework - Expression Language Dmitry Noskov
  • 11. Type conversion  Converter public interface Converter<S, T> { T convert(S source); }  ConversionService  http://static.springsource.org/spring/docs/3.0.x/spri ng-framework-reference/html/validation.html#core- convert Spring Framework - Expression Language Dmitry Noskov
  • 12. Object properties  #{person.name}  #{person.Name}  #{person.getName()} Spring Framework - Expression Language Dmitry Noskov
  • 13. Collections  #{list[0]}  #{list[0].name}  #{map[‘key’]} Spring Framework - Expression Language Dmitry Noskov
  • 14. Methods  #{‘Some Text’.substring(0, 2)}  #{‘Some Text’.startsWith(‘text’)}  #{“variable.toString()”} Spring Framework - Expression Language Dmitry Noskov
  • 15. Relational operators  #{5 == 5} or #{5 eq 5}  #{‘black’ > ’block’} or #{‘black’ gt ‘block’}  #{‘text’ instanceof T(int)}  #{'5.00' matches '^-?d+(.d{2})?$'} Spring Framework - Expression Language Dmitry Noskov
  • 16. Arithmetic operators  #{5 + 5}  #{(5 + 5) * 2}  #{17 / 5 % 3}  #{‘Hello’ + ‘ ‘ + ‘world’} Spring Framework - Expression Language Dmitry Noskov
  • 17. Logical operators  #{true or false}  #{!true}  #{not isUserInGroup(‘admin’)} Spring Framework - Expression Language Dmitry Noskov
  • 18. Assignment SimpleBean dima = new SimpleBean("Dima", 26); EvaluationContext context = new StandardEvaluationContext(dima); parser.parseExpression("name").setValue(context, "Dmitry"); parser.parseExpression("age=27").getValue(context); Spring Framework - Expression Language Dmitry Noskov
  • 19. Type operator  #{T(java.util.Date)}  #{T(String)}  #{T(int)}  accessing static class members  #{T(Math).PI}  #{T(Math).random()} Spring Framework - Expression Language Dmitry Noskov
  • 20. instanceof  #{‘text’ instanceof T(String)}  #{27 instanceof T(Integer)}  #{false instanceof T(Boolean)} Spring Framework - Expression Language Dmitry Noskov
  • 21. Constructor  #{new org.training.spel.Person(‘Misha’, 28)}  #{list.add(new org.training.spel.Person())} Spring Framework - Expression Language Dmitry Noskov
  • 22. Variable registration Map<String, Person> map = new HashMap<String, Person>(); map.put("Dima", new Person("Dima", 27)); map.put("Anya", new Person("Anya", 23)); ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariable("map", map); ctx.setVariable("anya", "Anya"); parser.parseExpression("#map['Dima']").getValue(ctx); parser.parseExpression("#map[#anya]").getValue(ctx); Spring Framework - Expression Language Dmitry Noskov
  • 23. If-then-else  #{person.age>50 ? ‘Old’ : ‘Young’}  #{person.name ? : ‘N/A’} Spring Framework - Expression Language Dmitry Noskov
  • 24. Safe navigation  #{address.city?.name}  #{person.name?.length()} Spring Framework - Expression Language Dmitry Noskov
  • 25. Collection selection  select all  #{list.?[age>20]}  #{list.?[name.startsWith(‘D’)]}  select first  #{list.^[age>20]}  select last  #{list.$[getAge()>20]} Spring Framework - Expression Language Dmitry Noskov
  • 26. Collection projection  select the names of all elements  #{list.![name]}  select the names length of all elements  #{list.![name.length()]} Spring Framework - Expression Language Dmitry Noskov
  • 27. Functions ExpressionParser parser = new SpelExpressionParser(); EvaluationContext context = new StandardEvaluationContext(); context.registerFunction("max", Collections.class. getDeclaredMethod("max", new Class[]{Collection.class})); parser.parseExpression("#max(#list.![age])").getValue(context); Spring Framework - Expression Language Dmitry Noskov
  • 28. Templating ExpressionParser parser = new SpelExpressionParser(); String value = parser.parseExpression( "Random number is #{T(java.lang.Math).random()}", new TemplateParserContext() ).getValue(String.class); But: parser.parseExpression("#{#primes.?[#this>10]}", …) Spring Framework - Expression Language Dmitry Noskov
  • 29. #root and #this  array of integer list.addAll(Arrays.asList(2,3,5,7,11,13,17)); p.parseExpression("#list.?[#this>10]").getValue(context);  list of age List<Person> list = new ArrayList<Person>(); p.parseExpression("#list.![age].?[#this>20]").getValue(context); Spring Framework - Expression Language Dmitry Noskov
  • 30. Using root object  unchanging StandardEvaluationContext context = new StandardEvaluationContext(new Person("Dima", 25)); parser.parseExpression("name").getValue(context);  changing parser.parseExpression("name").getValue(new Person("Dima", 27));  cached context StandardEvaluationContext context = new StandardEvaluationContext(new Person("Dima", 25)); parser.parseExpression("name").getValue(context, person1); parser.parseExpression("name").getValue(context, person2); Spring Framework - Expression Language Dmitry Noskov
  • 31. Access to Spring context <bean id="simpleBean" class="org.training.spel.Person" p:name="Misha" p:age="#{25+23}"/> ApplicationContext context = new ClassPathXmlApplicationContext("context.xml"); Person bean = context.getBean(Person.class); ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext evaluation = new StandardEvaluationContext(context); evaluation.addPropertyAccessor(new BeanFactoryAccessor()); parser.parseExpression("simpleBean").getValue(evaluation); Spring Framework - Expression Language Dmitry Noskov
  • 32. Wiring properties  simple @Value("#{systemProperties['locale']}") private Locale locale;  default @Value("#{systemProperties['locale']?:'RU'}") private Locale locale;  selective @Value("#{systemProperties['level']>2 ? gold : default}") private AccountRepository repository; Spring Framework - Expression Language Dmitry Noskov
  • 33. Information  Spring type conversion reference http://static.springsource.org/spring/docs/3.0.x/spring- framework-reference/html/validation.html#core-convert  Spring EL reference http://static.springsource.org/spring/docs/3.0.x/spring- framework-reference/html/expressions.html Spring Framework - Expression Language Dmitry Noskov
  • 34. Questions Spring Framework - Expression Language Dmitry Noskov
  • 35. The end http://www.linkedin.com/in/noskovd http://www.slideshare.net/analizator/presentations