In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to use Spring Expression Language, the article is very detailed, has a certain reference value, interested friends must read it!
Spring Expression Language (SpEL)
Is a powerful expression language that supports querying, manipulating runtime object graphs, as well as parsing logic and arithmetic expressions. SpEL can be used independently, whether or not you use the Spring framework.
1. Environmental preparation
Introduce dependencies:
Compile group: 'org.springframework', name:' spring-expression', version: '5.2.4.RELEASE'
Readers can choose the latest version or the appropriate version. Of course, you can also download the corresponding jar file. Before calling the following function, initialize a class-level property SpelExpression parser as follows:
Import org.springframework.expression.Expression;import org.springframework.expression.ExpressionParser;import org.springframework.expression.spel.standard.SpelExpressionParser;public class ElMain {private ExpressionParser parser; ElMain () {parser = new SpelExpressionParser ();} public static void main (String [] args) {ElMain elHelper = new ElMain (); elHelper.evaluateLiteralExpresssions ();} private static void print (Object message) {System.out.println (message) } 2.SpEL sample application
2.1. Parsing direct text
Private void evaluateLiteralExpresssions () {Expression exp = parser.parse_Expression ("'Hello World'"); String message = (String) exp.getValue (); print (message); exp = parser.parse_Expression ("6"); Integer value = exp.getValue (Integer.class); print (value*2);}
The string and numeric text are solved directly here.
2.2. Call the method on the direct text
/ * A function that tests method invocation on literals * / private void methodInvocationOnLiterals () {Expression exp = parser.parse_Expression ("'Hello World'.concat ('!')"); String message = (String) exp.getValue (); println (message); exp = parser.parse_Expression ("'Hello World'.length ()"); Integer size = exp.getValue (Integer.class); println (size) Exp = parser.parse_Expression ("'Hello World'.split ('') [0]"); message = (String) exp.getValue (); println (message);}
The example shows calling the public method of the Java String class directly on a string.
2.3. Access object properties and methods
/ * * A function that tests accessing properties of objects**/ private void accessingObjectProperties () {User user = new User ("John", "Doe", true, "john.doe@acme.com", 30); Expression exp = parser.parse_Expression ("firstName"); println ((String) exp.getValue (user)); exp = parser.parse_Expression ("isAdmin () = = false"); boolean isAdmin = exp.getValue (user, Boolean.class) Println (isAdmin); exp = parser.parse_Expression ("email.split ('@') [0]"); String emailId = exp.getValue (user, String.class); println (emailId); exp = parser.parse_Expression ("age"); Integer age = exp.getValue (user, Integer.class); println (age);}
Expressions can use the properties and methods of an object directly. We see that methods are used the same as properties, except that there are more call parentheses.
2.4. Perform various operations (comparison, logic, arithmetic)
SpEl supports the following operations:
Relation comparison operation: =,!, =
Logical operations: and, or, not
Arithmetic operation: +, -, /, *,%, ^
Private void operators () {User user = new User ("John", "Doe", true, "john.doe@acme.com", 30); Expression exp = parser.parse_Expression ("age > 18"); println (exp.getValue (user,Boolean.class)); exp = parser.parse_Expression ("age")
< 18 and isAdmin()"); println(exp.getValue(user,Boolean.class)); } 2.5.使用多个对象和变量 表达式不仅需要引用对象,而且可能需要引用多个不同类型的对象。我们可以把所有使用的对象都加入至上下文中。使用键值对的方式加入并引用。 private void variables() { User user = new User("John", "Doe", true, "john.doe@acme.com",30); Application app = new Application("Facebook", false); StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("user", user); context.setVariable("app", app); Expression exp = parser.parse_Expression("#user.isAdmin() and #app.isActive()"); Boolean result = exp.getValue(context,Boolean.class); println(result); } 2.6.调用自定义函数 SpEl也可以调用自定义的函数,用户可以扩展业务逻辑。下面首先定义一个函数: public class StringHelper { public static boolean isValid(String url){ return true; }} 下面在SpEl中调用isValid方法: private void customFunctions() { try { StandardEvaluationContext context = new StandardEvaluationContext(); context.registerFunction("isURLValid", StringHelper.class.getDeclaredMethod("isValid", new Class[] { String.class })); String expression = "#isURLValid('http://google.com')"; Boolean isValid = parser.parse_Expression(expression).getValue(context, Boolean.class); println(isValid); } catch (Exception e) { e.printStackTrace(); } }3.小结 通过示例介绍了SpEl中多种应用场景。读者可以利用这些功能实现更加灵活的功能应用。 Spring表达式语言SpEL Spring 表达式语言(简称SpEL):是一个支持运行时查询和操作对象图的强大的表达式语言。 语法类似于 EL:SpEL 使用 #{…} 作为定界符,所有在大框号中的字符都将被认为是 SpEL SpEL 为 bean 的属性进行动态赋值提供了便利. 通过 SpEL 可以实现: 通过 bean 的 id 对 bean 进行引用 调用方法以及引用对象中的属性 计算表达式的值 正则表达式的匹配 SpEL:字面量 字面量的表示: 整数:小数:科学计数法:String可以使用单引号或者双引号作为字符串的定界符号: 或Boolean: 如果仅仅是表示字面量,其实是没有必要使用Spring EL表达式的,这里仅仅演示一下而已,日常的开发中很少使用。 SpEL:引用 Bean、属性和方法 引用其他对象 但是我们更常用ref 来实现其他对象的引用 引用其他对象的属性Call other methods, you can also chain operation
Call static methods or static properties
Call the static method of a class through T (), which returns a Class Object, and then calls the corresponding method or property:
Operational symbols supported by SpEL
Arithmetic operator: +, -, *, /,%, ^
The plus sign can also be used as a string concatenation
Comparison operators:, =, =, lt, gt, eq, le, ge
Logical operation symbols: and, or, not, |
If-else operator:?: (ternary),?: (Elvis)
Variants of if-else
Regular expressions: matches
Example-xml-based approach
Package com.xgj.spel;/** * @ ClassName: Address * * @ Description: address Information * * @ author: Mr.Yang * * @ date: 8:29:12 * / public class Address {private String city; private String street; public String getCity () {return city;} public void setCity (String city) {this.city = city } public String getStreet () {return street;} public void setStreet (String street) {this.street = street;} @ Override public String toString () {return "Address [city=" + city + ", street=" + street + ", getClass () =" + getClass () + ", hashCode () =" + hashCode () + ", toString () =" + super.toString () + "]";}} package com.xgj.spel / * * @ ClassName: Car * * @ Description: vehicle * * @ author: Mr.Yang * * @ date: 8:30:01 * / public class Car {private String brand; private double price on April 7, 2018 / call static method or static property: call a static method of a class through T (), which will return a Class Object, and then call the corresponding method or property private long weight; public long getWeight () {return weight;} public void setWeight (long weight) {this.weight = weight;} public String getBrand () {return brand } public void setBrand (String brand) {this.brand = brand;} public double getPrice () {return price;} public void setPrice (double price) {this.price = price;} @ Override public String toString () {return "Car [brand=" + brand + ", price=" + price + ", weight=" + weight + "]";} package com.xgj.spel Public class Boss {private String name; private Car car; / / references the city private String city; of Address through Spring El / / through the price attribute of Car, and determines info. If car.price > = 500000, info is CEO, otherwise it is Staff private String info; public String getName () {return name;} public void setName (String name) {this.name = name;} public Car getCar () {return car } public void setCar (Car car) {this.car = car;} public String getCity () {return city;} public void setCity (String city) {this.city = city;} public String getInfo () {return info;} public void setInfo (String info) {this.info = info @ Override public String toString () {return "Boss [name=" + name + ", car=" + car + ", city=" + city + ", info=" + info + "]";}}
Configuration file:
Test class:
Package com.xgj.spel;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpelTest {public static void main (String [] args) {String configLocation = "com/xgj/spel/beans_spel.xml"; ApplicationContext ctx = new ClassPathXmlApplicationContext (configLocation); Car car = (Car) ctx.getBean ("car"); System.out.println (car); Boss boss = (Boss) ctx.getBean ("boss") System.out.println (boss);}}
Results:
2018-04-07 21 INFO [main] (AbstractApplicationContext.java:583)-Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4af6178d: startup date [Sat Apr 07 21:21:30 BOT 2018]; root of context hierarchy
2018-04-07 21 INFO [main] (XmlBeanDefinitionReader.java:317)-Loading XML bean definitions from class path resource [com/xgj/spel/beans_spel.xml]
Car [brand=Bench, price=700000.0, weight=14347]
Boss [name=Artisan, car=Car [brand=Bench, price=700000.0, weight=14347], city=NanJing, info=CEO]
Example-Annotation-based approach
We demonstrate it through an example of a database. Although you can load a parameter value from a configuration file through an Spring El expression, such as
@ Value ("# {properties ['jdbc.driverClassName']}")
Is it easy to make mistakes... . Spring provides a better way to context:property-placeholder.
Package com.xgj.spel.annotation;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;/** * @ ClassName: MyDataSource * * @ Description: data source @ Component annotation * * @ author: Mr.Yang * * @ date: 9:26:32 * / @ Componentpublic class MyDataSource {private String driverClass; private String url; private String username; private String password on April 7, 2018 Public String getDriverClass () {return driverClass } / * * @ Title: setDriverClass * * @ Description: @ Value annotation automatically injects the value of the corresponding attribute in the attribute configuration file * * @ param driverClass * * @ return: void * / @ Value ("${jdbc.driverClassName}") public void setDriverClass (String driverClass) {this.driverClass = driverClass } public String getUrl () {return url;} @ Value ("${jdbc.url}") public void setUrl (String url) {this.url = url;} public String getUsername () {return username;} / / @ Value ("$(jdbc.username)") @ Value ("${jdbc.username}") public void setUsername (String username) {this.username = username } public String getPassword () {return password;} @ Value ("${jdbc.password}") public void setPassword (String password) {this.password = password;} @ Override public String toString () {return "MyDataSource [driverClass=" + driverClass + ", url=" + url + ", username=" + username + ", password=" + password + "]";}}
Db_mysql.properties
Jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/artisanjdbc.username=artisanjdbc.password=artisanpackage com.xgj.spel.annotation;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestCase {@ Test public void test () {String configurationLocation = "com/xgj/spel/annotation/beans_anno.xml"; ApplicationContext ctx = new ClassPathXmlApplicationContext (configurationLocation); MyDataSource myDataSource = (MyDataSource) ctx.getBean ("myDataSource") System.out.println (myDataSource); System.out.println ("driverClassName:" + myDataSource.getDriverClass ()); System.out.println ("url:" + myDataSource.getUrl ()); System.out.println ("username:" + myDataSource.getUsername ()); System.out.println ("password:" + myDataSource.getPassword ());}}
Running result
2018-04-07 23 AbstractApplicationContext.java:583 37 INFO [main] (AbstractApplicationContext.java:583)-Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@761df304: startup date [Sat Apr 07 23:37:11 BOT 2018]; root of context hierarchy
2018-04-07 23 XmlBeanDefinitionReader.java:317 37 INFO [main] (XmlBeanDefinitionReader.java:317)-Loading XML bean definitions from class path resource [com/xgj/spel/annotation/beans_anno.xml]
MyDataSource [driverClass=com.mysql.jdbc.Driver, url=jdbc:mysql://localhost:3306/artisan, username=artisan, password=artisan]
DriverClassName:com.mysql.jdbc.Driver
Url:jdbc:mysql://localhost:3306/artisan
Username:artisan
Password:artisan
The above is all the contents of the article "how to use Spring Expression Language". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.