Spring之Spel表达式
正常业务场景一般不用这个技术,但需要知道有这么个东西支持Spring。
记忆力不好,抄了些套路代码便于以后用到。
package com.paic.phssp.springtest.spel; import java.util.Arrays;
import java.util.List; public class Account {
private String name;
private int footballCount;
private Friend friend;
private List<Friend> friends; public Account(String name) {
this.name = name;
} public String getName() {
return name;
} public void setFootballCount(int footballCount) {
this.footballCount = footballCount;
} public void addFriend(Friend friend) { this.friend = friend;
} public int getFootballCount() {
return footballCount;
} public Friend getFriend() {
return friend;
} public void setFriend(Friend friend) {
this.friend = friend;
} public List<Friend> getFriends() {
return friends;
} public void setFriends(List<Friend> friends) {
this.friends = friends;
} public void read(){
System.out.println("读书");
} public void addFriendNames(String ... friendNames){
System.out.println("friendNames="+ Arrays.toString(friendNames));
}
}
package com.paic.phssp.springtest.spel; public class Friend {
private String name; public Friend(String name) {
this.name = name;
} public String getName() {
return name;
}
}
package com.paic.phssp.springtest.spel; import com.paic.phssp.springtest.proxy.cglib.HeroCglibProxyFactory;
import com.paic.phssp.springtest.proxy.cglib.WickedLittleMage;
import com.paic.phssp.springtest.proxy.jdk.HeroProxyFactory;
import com.paic.phssp.springtest.proxy.jdk.IHero;
import com.paic.phssp.springtest.proxy.jdk.MonkeyHero;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.test.context.junit4.SpringRunner; import java.util.*; @RunWith(SpringRunner.class)
@SpringBootTest
public class SpelTest { @Test
public void testTextEl() {
//文字表达式
ExpressionParser parser = new SpelExpressionParser(); //字符串解析
String str = (String) parser.parseExpression("'你好'").getValue();
System.out.println(str); //整型解析
int intVal = (Integer) parser.parseExpression("0x2F").getValue();
System.out.println(intVal); //双精度浮点型解析
double doubleVal = (Double) parser.parseExpression("4329759E+22").getValue();
System.out.println(doubleVal); //布尔型解析
boolean booleanVal = (boolean) parser.parseExpression("true").getValue();
System.out.println(booleanVal); /* 你好
47
4.329759E28
true*/
} @Test
public void testObjEl() {
//初始化对象
Account account = new Account("Deniro");
account.setFootballCount(10);
account.addFriend(new Friend("Jack")); //解析器
ExpressionParser parser = new SpelExpressionParser();
//解析上下文
EvaluationContext context = new StandardEvaluationContext(account); //获取不同类型的属性
String name = (String) parser.parseExpression("name").getValue(context);
System.out.println(name);
int count = (Integer) parser.parseExpression("footballCount+1").getValue(context);
System.out.println(count); //获取嵌套类中的属性
String friend = (String) parser.parseExpression("friend.name").getValue(context);
System.out.println(friend); /*Deniro
11
Jack*/ //安全导航操作符,能够避免空指针异常
account.setFriend(null);
friend = (String) parser.parseExpression("friend?.name").getValue(context,String.class);
System.out.println("friendName:" + friend);//friendName:null } @Test
public void testArrMapListEl() {
//解析器
ExpressionParser parser = new SpelExpressionParser(); //解析一维数组
int[] oneArray = (int[]) parser.parseExpression("new int[]{3,4,5}").getValue();
System.out.println("一维数组开始:");
for (int i : oneArray) {
System.out.print(i);
}
System.out.println();
System.out.println("一维数组结束"); /* 一维数组开始:
345
一维数组结束*/ //这里会抛出 SpelParseException
// int[][] twoArray = (int[][]) parser.parseExpression("new int[][]{3,4,5}{3,4,5}")
// .getValue(); //解析 list
List list = (List) parser.parseExpression("{3,4,5}").getValue();
System.out.println("list:" + list);
//list:[3, 4, 5] //解析 Map
Map map = (Map) parser.parseExpression("{account:'deniro',footballCount:10}").getValue();
System.out.println("map:" + map);
//map:{account=deniro, footballCount=10} //解析对象中的 list
final Account account = new Account("Deniro");
Friend friend1 = new Friend("Jack");
Friend friend2 = new Friend("Rose");
List<Friend> friends = new ArrayList<>();
friends.add(friend1);
friends.add(friend2);
account.setFriends(friends); EvaluationContext context = new StandardEvaluationContext(account);
String friendName = (String) parser.parseExpression("friends[0].name").getValue(context);
System.out.println("friendName:" + friendName);
//friendName:Jack
} @Test
public void testMethodEl() {
//解析器
ExpressionParser parser = new SpelExpressionParser(); //调用 String 方法
boolean isEmpty = parser.parseExpression("'Hi,everybody'.contains('Hi')").getValue(Boolean.class);
System.out.println("isEmpty:" + isEmpty); /**
* 调用对象相关方法
*/
final Account account = new Account("Deniro");
EvaluationContext context = new StandardEvaluationContext(account); //调用公开方法
parser.parseExpression("setFootballCount(11)").getValue(context, Account.class);
System.out.println("getFootballCount:" + account.getFootballCount()); //调用私有方法,抛出 SpelEvaluationException: EL1004E: Method call: Method write() cannot be found on net.deniro
// .spring4.spel.Account type
// parser.parseExpression("write()").getValue(context,Boolean
// .class); //调用静态方法
parser.parseExpression("read()").getValue(context, Account.class); //调用待可变参数的方法
parser.parseExpression("addFriendNames('Jack','Rose')").getValue(context, Account.class); /* isEmpty:true
getFootballCount:11
读书
friendNames=[Jack, Rose]*/
} @Test
public void testRelationEl() {
//关系操作符
//解析器
ExpressionParser parser = new SpelExpressionParser(); //数值比较
boolean result = parser.parseExpression("2>1").getValue(Boolean.class);
System.out.println("2>1:" + result); //2>1:true //字符串比较
result = parser.parseExpression("'z'>'a'").getValue(Boolean.class);
System.out.println("'z'>'a':" + result); //'z'>'a':true //instanceof 运算符
result = parser.parseExpression("'str' instanceof T(String)").getValue(Boolean.class);
System.out.println("'str' 是否为字符串 :" + result); //'str' 是否为字符串 :true result = parser.parseExpression("1 instanceof T(Integer)").getValue(Boolean.class);
System.out.println("1 是否为整型 :" + result); //1 是否为整型 :true //正则表达式
result = parser.parseExpression("22 matches '\\d{2}'").getValue(Boolean.class);
System.out.println("22 是否为两位数字 :" + result); //22 是否为两位数字 :true
} @Test
public void testlogicEl() {
//解析器
ExpressionParser parser = new SpelExpressionParser(); //与操作
boolean result = parser.parseExpression("true && true").getValue(Boolean.class);
System.out.println("与操作:" + result); //或操作
result = parser.parseExpression("true || false").getValue(Boolean.class);
System.out.println("或操作:" + result); parser.parseExpression("true or false").getValue(Boolean.class);
System.out.println("或操作(or 关键字):" + result); //非操作
result = parser.parseExpression("!false").getValue(Boolean.class);
System.out.println("非操作:" + result);
} @Test
public void testOperateEl() {
ExpressionParser parser = new SpelExpressionParser();
//加法运算
Integer iResult = parser.parseExpression("2+3").getValue(Integer.class);
System.out.println("加法运算:" + iResult); String sResult = parser.parseExpression("'Hi,'+'everybody'").getValue(String.class);
System.out.println("字符串拼接运算:" + sResult); //减法运算
iResult = parser.parseExpression("2-3").getValue(Integer.class);
System.out.println("减法运算:" + iResult); //乘法运算
iResult = parser.parseExpression("2*3").getValue(Integer.class);
System.out.println("乘法运算:" + iResult); //除法运算
iResult = parser.parseExpression("4/2").getValue(Integer.class);
System.out.println("除法运算:" + iResult); Double dResult = parser.parseExpression("4/2.5").getValue(Double.class);
System.out.println("除法运算:" + dResult); //求余运算
iResult = parser.parseExpression("5%2").getValue(Integer.class);
System.out.println("求余运算:" + iResult); //三元运算符
boolean result=parser.parseExpression("(1+2) == 3?true:false").getValue(Boolean.class);
System.out.println("result:"+result);
} @Test
public void testClassEl() {
ExpressionParser parser = new SpelExpressionParser(); //加载 java.lang.Integer
Class integerClass=parser.parseExpression("T(Integer)").getValue(Class
.class);
System.out.println(integerClass==java.lang.Integer.class); //加载 net.deniro.spring4.spel.Account
Class accountClass=parser.parseExpression("T(com.paic.phssp.springtest.spel.Account)")
.getValue(Class
.class);
System.out.println(accountClass==com.paic.phssp.springtest.spel.Account.class); //调用类静态方法
double result = (double) parser.parseExpression("T(Math).abs(-2.5)").getValue();
System.out.println("result:" + result); //创建对象操作符
Account account=parser.parseExpression("new com.paic.phssp.springtest.spel.Account" +
"('Deniro')").getValue(Account.class);
System.out.println("name:"+account.getName());
} @Test
public void testVariableEl(){
Account account = new Account("Deniro"); ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext(account); //定义一个新变量,名为 newVal
context.setVariable("newVal", "Jack"); //获取变量 newVal 的值,并赋值给 User 的 name 属性
parser.parseExpression("name=#newVal").getValue(context);
System.out.println("getName:" + account.getName()); //this 操作符表示集合中的某个元素
List<Double> scores = new ArrayList<>();
scores.addAll(Arrays.asList(23.1, 82.3, 55.9));
context.setVariable("scores", scores);//在上下文中定义 scores 变量
List<Double> scoresGreat80 = (List<Double>) parser.parseExpression("#scores.?[#this>80]").getValue(context);
System.out.println("scoresGreat80:" + scoresGreat80);
} @Test
public void testCollectSelectEl(){
//集合选择表达式
ExpressionParser parser = new SpelExpressionParser();
List list = (List) parser.parseExpression("{3,4,5}").getValue(); //----------------过滤 list 集合中的元素
final StandardEvaluationContext listContext = new StandardEvaluationContext(list);
List<Integer> great4List = (List<Integer>) parser.parseExpression("?[#this>4]").getValue(listContext);
System.out.println("great4List:" + great4List); //获取匹配元素中的第一个值
Integer first = (Integer) parser.parseExpression("^[#this>2]").getValue(listContext);
System.out.println("first:" + first); //获取匹配元素中的最后一个值
Integer end = (Integer) parser.parseExpression("$[#this>2]") .getValue(listContext);
System.out.println("end:" + end); //----------------过滤 Map
Map<String, Double> rank = new HashMap<String, Double>();
rank.put("Deniro", 96.5);
rank.put("Jack", 85.3);
rank.put("Lily", 91.1); EvaluationContext context = new StandardEvaluationContext();
context.setVariable("Rank", rank);
//value 大于 90
Map<String,Double> rankGreat95= (Map<String, Double>) parser.parseExpression("#Rank.?[value>90]").getValue(context);
System.out.println("rankGreat95:" + rankGreat95); //key 按字母顺序,排在 L 后面
Map<String,Double> afterL= (Map<String, Double>) parser.parseExpression("#Rank.?[key>'L']").getValue(context);
System.out.println("afterL:"+afterL);
}
}
参考:
https://www.jianshu.com/p/5537b2c86acd
Spring之Spel表达式的更多相关文章
- Spring Security -SpEL表达式
Spring Security -SpEL表达式 开启SpEL表达式 <!-- use-expressions是否开启 SpEL表达式 o.s.s.web.access.expression.W ...
- Spring系列.SpEL表达式
Spring表达式语言 SpEL语言是一种强大的表达式语言,支持在运行时查询和操作对象.SpEL表达式不一定要创建IOC容器后才能使用.用户完全可以单独调用SpEL的API来独立的使用时SpEL表达式 ...
- Spring学习-- SpEL表达式
Spring 表达式语言(简称SpEL):是一个支持运行时查询和操作对象图的强大的表达式语言. 语法类似于 EL:SpEL 使用 #{...} 作为定界符 , 所有在大括号中的字符都将被认为是 SpE ...
- Spring实战学习笔记之SpEL表达式
在Spring XML配置文件中装配Bean的属性和构造参数都是静态的,而在运行期才知道装配的值,就可以使用SpEL实现 SpEL表达式的首要目标是通过计算获得某个值. ...
- Spring SpEL表达式的理解
Spring的IOC本质就一个容器,也就是一个对象的工厂,我们通过配置文件注册我们的Bean对象,通过他进行对象的组装与床架. SpEL表达式就是一种字符串编程,类似于JS里面的EVAL的作用,通过它 ...
- 【spring boot】SpringBoot初学(2.2)– SpEL表达式读取properties属性到Java对象
前言 github: https://github.com/vergilyn/SpringBootDemo 代码位置:(注意测试方法在,test下的SpelValueApplicationTest.c ...
- Spring 缓存注解 SpEL 表达式解析
缓存注解上 key.condition.unless 等 SpEL 表达式的解析 SpEl 支持的计算变量: 1)#ai.#pi.#命名参数[i 表示参数下标,从 0 开始] 2)#result:Ca ...
- SpringBoot SpEL表达式注入漏洞-分析与复现
目录 0x00前言 0x01触发原因 0x02调试分析 0x03补丁分析 0x04参考文章 影响版本: 1.1.0-1.1.12 1.2.0-1.2.7 1.3.0 修复方案:升至1.3.1或以上版本 ...
- 从头认识Spring-1.14 SpEl表达式(1)-简单介绍与嵌入值
这一章节我们来讨论一下SpEl表达式的简单介绍与嵌入值. 1.SpEl表达式简单介绍 Spring Excpression Language (SpEL)语言支持在执行时操作和查询对象 事实上就是在执 ...
随机推荐
- 如何用Tensorflow训练模型成pb文件和和如何加载已经训练好的模型文件
这篇薄荷主要是讲了如何用tensorflow去训练好一个模型,然后生成相应的pb文件.最后会将如何重新加载这个pb文件. 首先先放出PO主的github: https://github.com/ppp ...
- 谷歌zxing 二维码生成工具
一.加入maven依赖 <!-- 谷歌zxing 二维码 --> <dependency> <groupId>com.google.zxing</groupI ...
- Python3基础 list [] 创建空列表
Python : 3.7.0 OS : Ubuntu 18.04.1 LTS IDE : PyCharm 2018.2.4 Conda ...
- 【修改密码】Linux下修改Mysql的用户(root)的密码
修改的用户都以root为列.一.拥有原来的myql的root的密码: 方法一:在mysql系统外,使用mysqladmin# mysqladmin -u root -p password " ...
- P4306 [JSOI2010]连通数
思路 要求求每个点能到达的点数就是传递闭包 然后n^3Floyd可做,但是n=2000,然后bitset压位 复杂度\(O(\frac{n^3}{32})\),能过 代码 #include <c ...
- P2257 YY的GCD(莫比乌斯反演)
第一次做莫比乌斯反演,推式子真是快乐的很啊(棒读) 前置 若函数\(F(n)\)和\(f(d)\)存在以下关系 \[ F(n)=\sum_{n|d}f(d) \] 则可以推出 \[ f(n)=\sum ...
- Hadoop技术内幕1——源代码环境准备
Hadoop核心 1.HDFS:高容错性.高伸缩性……,允许用户将Hadoop部署在廉价的硬件上,构建分布式系统 2.MapReduce:分布式计算框架,允许用户在不了解分布式系统底层细节的情况下,开 ...
- 常用模块(subprocess/hashlib/configparser/logging/re)
一.subprocess(用来执行系统命令) import os cmd = r'dir D:xxx | findstr "py"' # res = subprocess.Pope ...
- CentOS7使用firewalld和selinux
转载自莫小安的博客:https://www.cnblogs.com/moxiaoan/p/5683743.html 如何查看和使用selinux https://blog.csdn.net/edide ...
- Leetcode88_Merge Sorted Array_Easy
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: T ...