SpEL表达式使用方法

【SpringBoot3】SpEL表达式详细使用说明 SpEL(Spring Expression Language)是Spring框架提供的一种功能强大的表达式语言,用于在运行时查询和操作对象。 主要特点和用途包括: 1. 简洁性:SpEL表达式使用简洁的语法,使得在Spring配置和代码中能够更简洁地表达复杂的逻辑。 2. 动态性:SpEL表达式能够在运行时动态地解析和执行,从而提供了更大的灵活性。 3. 强大的功能:SpEL表达式支持各种功能,如方法调用、字符串模板、集合操作、逻辑运算等,使得在Spring配置和代码中能够完成复杂的逻辑处理。 阅读详情
AI摘要

本文深入探讨Spring Expression Language (SpEL)的使用方法与高级特性,包括基本使用、编程方式执行、配置、表达式语法、类型操作、对象构造及模板表达式等内容。

1 SpEL简介

SpEL(Spring Expression Language)是一种用于在Spring框架中进行数据绑定和执行业务逻辑的表达式语言。Spring EL提供了一种简洁、灵活和强大的方式来访问对象的属性、调用方法、执行运算和逻辑判断等操作。

官方文档:https://docs.spring.io/spring-framework/reference/core/expressions.html

2 基本使用

2.1 通过@Value注解使用

可以将@Value注解加在字段,方法,方法参数,构造方法参数上使用,${…}表示直接读取上下文的属性值,而#{…}就表示使用SpEL进行运算。

字段示例:

public class FieldValueTestBean {

	@Value("#{systemProperties['user.region'] }")
	private String defaultLocale;

    private String defaultTimezone;

	public void setDefaultLocale(String defaultLocale) {
		this.defaultLocale = defaultLocale;
	}
}

方法示例:

public class PropertyValueTestBean {

	private String defaultLocale;

	@Value("#{ systemProperties['user.region'] }")
	public void setDefaultLocale(String defaultLocale) {
		this.defaultLocale = defaultLocale;
	}

	public String getDefaultLocale() {
		return this.defaultLocale;
	}
}

@Autowired方法示例:

public class SimpleMovieLister {

	private MovieFinder movieFinder;
	private String defaultLocale;

	@Autowired
	public void configure(MovieFinder movieFinder,
			@Value("#{ systemProperties['user.region'] }") String defaultLocale) {
		this.movieFinder = movieFinder;
		this.defaultLocale = defaultLocale;
	}

	// ...
}

构造方法示例:

public class MovieRecommender {

	private String defaultLocale;

	private CustomerPreferenceDao customerPreferenceDao;

	public MovieRecommender(CustomerPreferenceDao customerPreferenceDao,
			@Value("#{systemProperties['user.country']}") String defaultLocale) {
		this.customerPreferenceDao = customerPreferenceDao;
		this.defaultLocale = defaultLocale;
	}

	// ...
}

2.2 编程方式执行SpEL

2.2.1 基本使用

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World'"); 
String message = (String) exp.getValue(); // "Hello World"

2.2.2 设置根对象

Inventor tesla = new Inventor();
tesla.setName("Nikola Tesla");

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("name"); // Parse name as an expression
String name = (String) exp.getValue(tesla); // "Nikola Tesla"

2.2.3 设置上下文类型

以上的例子中,会创建一个上下文(EvaluationContext),默认实现类为StandardEvaluationContext
上下文接口有两种实现:

  • StandardEvaluationContext 完整的上下文功能
  • SimpleEvaluationContext 精简版的上下文,去除了Java类型参照、构造器、Bean参照等功能
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();

Inventor tesla = new Inventor();
tesla.setName("Nikola Tesla");

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("name"); // Parse name as an expression
String name = (String) exp.getValue(context, tesla); // "Nikola Tesla"

2.2.4 SpEL配置

可通过SpelParserConfiguration的构造方法,设置SpEL相关的配置, 例如:

class Demo {
	public List<String> list;
}

// 开启空对象自动初始化,开启集合自动增长
SpelParserConfiguration config = new SpelParserConfiguration(true, true);
ExpressionParser parser = new SpelExpressionParser(config);

ExpressionParser parser = new SpelExpressionParser(config);
Expression expression = parser.parseExpression("list[3]");
Demo demo = new Demo();
Object o = expression.getValue(demo); // 将不会报空指针异常,list会自动初始化, 并且将包含4个元素, 每个元素为空字符串

可以配置的功能有:

  • autoGrowNullReferences 开启自动生成对象,默认 false
  • autoGrowCollections 开启集合自动增长,默认 false
  • maximumAutoGrowSize 集合增长最大长度,默认 Integer.MAX_VALUE
  • maximumExpressionLength 表达式最大长度,默认 1000
  • compilerMode 开启预编译, 默认 OFF

2.2.4 编译SpEL

SpEL编译功能默认是关闭的,如果对性能有要求,那么可以开启预编译功能,

  • SpelCompilerMode.OFF 默认关闭
  • SpelCompilerMode.IMMEDIATE 立即编译,在第一次使用时就会编译
  • SpelCompilerMode.MIXED 混合编译,再使用几次后才会尝试编译,如果编译出错,就会用上次的编译成功的结果
SpelParserConfiguration config = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE,
		this.getClass().getClassLoader());

SpelExpressionParser parser = new SpelExpressionParser(config);
Expression expr = parser.parseExpression("payload");
MyMessage message = new MyMessage();
Object payload = expr.getValue(message);

3 表达式用法

3.1 字面量

  • String 使用单引号包裹
  • Number 使用int、long、float、double表示
  • Boolean true/false
  • Null null
xpressionParser parser = new SpelExpressionParser();

// evaluates to "Hello World"
String helloWorld = (String) parser.parseExpression("'Hello World'").getValue();

// evaluates to "Tony's Pizza"
String pizzaParlor = (String) parser.parseExpression("'Tony''s Pizza'").getValue();

double avogadrosNumber = (Double) parser.parseExpression("6.0221415E+23").getValue();

// evaluates to 2147483647
int maxValue = (Integer) parser.parseExpression("0x7FFFFFFF").getValue();

boolean trueValue = (Boolean) parser.parseExpression("true").getValue();

Object nullValue = parser.parseExpression("null").getValue();

3.2 属性、数组、列表、字典、索引

3.2.1 直接访问

通过对象.属性即可快速访问属性

// evaluates to 1856
int year = (Integer) parser.parseExpression("birthdate.year + 1900").getValue(context);

String city = (String) parser.parseExpression("placeOfBirth.city").getValue(context);

属性访问对首字母大小写是不敏感的,所以上面的表达式也可以写成"Birthdate.Year + 1900",“PlaceOfBirth.City”。
另外可以通过getter来访问,比如 “getPlaceOfBirth().getCity()”

通过中括号加数字来访问数组、列表的指定的元素

xpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();

// Inventions Array

// evaluates to "Induction motor"
String invention = parser.parseExpression("inventions[3]").getValue(
		context, tesla, String.class);

// Members List

// evaluates to "Nikola Tesla"
String name = parser.parseExpression("members[0].name").getValue(
		context, ieee, String.class);

// List and Array navigation
// evaluates to "Wireless communication"
String invention = parser.parseExpression("members[0].inventions[6]").getValue(
		context, ieee, String.class);

通过中括号加键名访问字典的元素

// Officer's Dictionary

Inventor pupin = parser.parseExpression("officers['president']").getValue(
		societyContext, Inventor.class);

// evaluates to "Idvor"
String city = parser.parseExpression("officers['president'].placeOfBirth.city").getValue(
		societyContext, String.class);

// setting values
parser.parseExpression("officers['advisors'][0].placeOfBirth.country").setValue(
		societyContext, "Croatia");

3.2.2 集合、字典过滤

使用.?[选择表达式]可以方便的对数组、集合、字典进行过滤,类似于Java Stream的filter方法

List<Inventor> list = (List<Inventor>) parser.parseExpression(
		"members.?[nationality == 'Serbian']").getValue(societyContext);
		
Map newMap = parser.parseExpression("#map.?[value < 27]").getValue(Map.class);

.^[选择表达式]表示只取第一个,.$[选择表达式]表示只取最后一个

Inventor first = (Inventor) parser.parseExpression(
		"members.^[nationality == 'Serbian']").getValue(societyContext);
		
Inventor last= (Inventor) parser.parseExpression(
		"members.$[nationality == 'Serbian']").getValue(societyContext);

3.2.3 集合投影

使用.![投影表达式]可以方便的对数组、集合、字典进行转换成别的集合,类似于Java Stream的map方法

// evaluates to ["Smiljan", "Idvor"]
List placesOfBirth = parser.parseExpression("members.![placeOfBirth.city]")
		.getValue(societyContext, List.class);

3.3 定义列表、字典、数组

定义列表

// evaluates to a Java list containing the four numbers
List numbers = (List) parser.parseExpression("{1,2,3,4}").getValue(context);
List listOfLists = (List) parser.parseExpression("{{'a','b'},{'x','y'}}").getValue(context);

定义字典

// evaluates to a Java map containing the two entries
Map inventorInfo = (Map) parser.parseExpression("{name:'Nikola',dob:'10-July-1856'}").getValue(context);

Map mapOfMaps = (Map) parser.parseExpression("{name:{first:'Nikola',last:'Tesla'},dob:{day:10,month:'July',year:1856}}").getValue(context);

定义数组

// 
int[] numbers1 = (int[]) parser.parseExpression("new int[4]").getValue(context);

// Array with initializer
int[] numbers2 = (int[]) parser.parseExpression("new int[] {1, 2, 3}").getValue(context);

// Multi dimensional array
int[][] numbers3 = (int[][]) parser.parseExpression("new int[4][5]").getValue(context);

初始化数组的表达式是无法预编译的

3.4 执行方法

和调用Java的方法一样,在SpEL中也是可以直接调用对象的方法的

// string literal, evaluates to "bc"
String bc = parser.parseExpression("'abc'.substring(1, 3)").getValue(String.class);

// evaluates to true
boolean isMember = parser.parseExpression("isMember('Mihajlo Pupin')").getValue(
		societyContext, Boolean.class);

3.5 运算符

3.5.1 关系运算

// evaluates to true
boolean trueValue = parser.parseExpression("2 == 2").getValue(Boolean.class);

// evaluates to false
boolean falseValue = parser.parseExpression("2 < -5.0").getValue(Boolean.class);

// evaluates to true
boolean trueValue = parser.parseExpression("'black' <= 'block'").getValue(Boolean.class); 

// evaluates to true
boolean falseValue = parser.parseExpression("'abc' > null").getValue(Boolean.class);

// uses CustomValue:::compareTo
boolean trueValue = parser.parseExpression("new CustomValue(2) > new CustomValue(1)").getValue(Boolean.class); 

除了用符号外,还可以用文本代替:

  • lt (<)
  • gt (>)
  • le (<=)
  • ge (>=)
  • eq (==)
  • ne (!=)

除了以上的关系运算,还支持between, instanceof, matches 关系运算

boolean result;

// evaluates to true
result = parser.parseExpression(
		"1 between {1, 5}").getValue(Boolean.class);

// evaluates to true
result = parser.parseExpression(
		"'elephant' between {'aardvark', 'zebra'}").getValue(Boolean.class);

// evaluates to true
result = parser.parseExpression(
		"123 instanceof T(Integer)").getValue(Boolean.class);

// evaluates to true
result = parser.parseExpression(
		"'5.00' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);

3.5.2 逻辑运算

SpEL 支持一下逻辑运算

  • 与 (and, &&)
  • 或 (or , ||)
  • 非 ( not, !)
// -- AND --

// evaluates to false
boolean falseValue = parser.parseExpression("true and false").getValue(Boolean.class);

// evaluates to true
String expression = "isMember('Nikola Tesla') and isMember('Mihajlo Pupin')";
boolean trueValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);

// -- OR --

// evaluates to true
boolean trueValue = parser.parseExpression("true or false").getValue(Boolean.class);

// evaluates to true
String expression = "isMember('Nikola Tesla') or isMember('Albert Einstein')";
boolean trueValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);

// -- NOT --

// evaluates to false
boolean falseValue = parser.parseExpression("!true").getValue(Boolean.class);

// -- AND and NOT --

String expression = "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')";
boolean falseValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);

3.5.3 字符串操作

+ 号表示字符串拼接,- 号表示单字符的ASCII码减去后的新值, * 号表示重复

// -- Concatenation --

// evaluates to "hello world"
String helloWorld = parser.parseExpression("'hello' + ' ' + 'world'")
		.getValue(String.class);

// -- Character Subtraction --

// evaluates to 'a'
char ch = parser.parseExpression("'d' - 3")
		.getValue(char.class);

// -- Repeat --

// evaluates to "abcabc"
String repeated = parser.parseExpression("'abc' * 2")
		.getValue(String.class);

3.5.4 数学运算

SpEL中支持以下数学运算

  • 加 (+)
  • 减(-)
  • 自增 (++)
  • 自减 (--)
  • 乘 (*)
  • 除 (/ , div)
  • 取模 (% , mod)
  • 指数幂 (^)
Inventor inventor = new Inventor();
EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();

// -- Addition --

int two = parser.parseExpression("1 + 1").getValue(int.class);  // 2

// -- Subtraction --

int four = parser.parseExpression("1 - -3").getValue(int.class);  // 4

double d = parser.parseExpression("1000.00 - 1e4").getValue(double.class);  // -9000

// -- Increment --

// The counter property in Inventor has an initial value of 0.

// evaluates to 2; counter is now 1
two = parser.parseExpression("counter++ + 2").getValue(context, inventor, int.class);

// evaluates to 5; counter is now 2
int five = parser.parseExpression("3 + ++counter").getValue(context, inventor, int.class);

// -- Decrement --

// The counter property in Inventor has a value of 2.

// evaluates to 6; counter is now 1
int six = parser.parseExpression("counter-- + 4").getValue(context, inventor, int.class);

// evaluates to 5; counter is now 0
five = parser.parseExpression("5 + --counter").getValue(context, inventor, int.class);

// -- Multiplication --

six = parser.parseExpression("-2 * -3").getValue(int.class);  // 6

double twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(double.class);  // 24.0

// -- Division --

int minusTwo = parser.parseExpression("6 / -3").getValue(int.class);  // -2

double one = parser.parseExpression("8.0 / 4e0 / 2").getValue(double.class);  // 1.0

// -- Modulus --

int three = parser.parseExpression("7 % 4").getValue(int.class);  // 3

int oneInt = parser.parseExpression("8 / 5 % 2").getValue(int.class);  // 1

// -- Exponential power --

int maxInt = parser.parseExpression("(2^31) - 1").getValue(int.class);  // Integer.MAX_VALUE

int minInt = parser.parseExpression("-2^31").getValue(int.class);  // Integer.MIN_VALUE

// -- Operator precedence --

int minusTwentyOne = parser.parseExpression("1+2-3*8").getValue(int.class);  // -21

3.5.5 赋值运算

在SpEL中也可以通过=表达式或者setValue方法执行对某个变量赋值的操作

Inventor inventor = new Inventor();
EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();

// 通过setValue方法赋值
parser.parseExpression("name").setValue(context, inventor, "Aleksandar Seovic");

// 通过 = 在表达式中赋值
String aleks = parser.parseExpression(
		"name = 'Aleksandar Seovic'").getValue(context, inventor, String.class);

3.5.6 三元运算

SpEL也支持 boolean ? trueValue : falseValue 形式的三元运算

String falseString = parser.parseExpression(
		"false ? 'trueExp' : 'falseExp'").getValue(String.class);

3.5.7 Elvis(埃尔维斯) 运算

埃尔维斯运算符是三元运算符语法的一种简化形式,以下示例中当name为null或者空字符串时,返回"Unknown"

ExpressionParser parser = new SpelExpressionParser();

String name = parser.parseExpression("name?:'Unknown'").getValue(new Inventor(), String.class);
System.out.println(name);  // 'Unknown'

3.5.8 Safe Navigation(安全导航)

Safe Navigation Operator(安全导航操作符)?.是一种用于处理可能为 null 的对象引用的操作符。它可以在访问可能为 null 的对象成员时避免空指针异常。

// evaluates to null - does not throw NullPointerException
city = parser.parseExpression("placeOfBirth?.city") 
		.getValue(context, tesla, String.class);

也可用于数组、集合、字典的顾虑和投影

  • 安全过滤: ?.?[过滤表达式]
  • 安全首位: ?.\^[过滤表达式]
  • 安全末位: ?.$[过滤表达式]
  • 安全投影: ?.![投影表达式]

安全导航还可以连用

#person?.address?.city

3.5.9 运算符重载

默认情况下,在 SpEL 的操作枚举(加法、减法、除法、乘法、取模和幂)中定义的数学运算支持像数字这样的简单类型。通过提供一个OperatorOverloader的实现,表达式语言可以在其他类型上支持这些操作。
例如,如果我们想要重载加法运算符,以便使用+符号将两个列表连接起来,我们可以如下实现一个自定义的OperatorOverloader。

pubic class ListConcatenation implements OperatorOverloader {

	@Override
	public boolean overridesOperation(Operation operation, Object left, Object right) {
		return (operation == Operation.ADD &&
				left instanceof List && right instanceof List);
	}

	@Override
	public Object operate(Operation operation, Object left, Object right) {
		if (operation == Operation.ADD &&
				left instanceof List list1 && right instanceof List list2) {

			List result = new ArrayList(list1);
			result.addAll(list2);
			return result;
		}
		throw new UnsupportedOperationException(
			"No overload for operation %s and operands [%s] and [%s]"
				.formatted(operation, left, right));
	}
}

StandardEvaluationContext context = new StandardEvaluationContext();
context.setOperatorOverloader(new ListConcatenation());

// evaluates to a new list: [1, 2, 3, 4, 5]
parser.parseExpression("{1, 2, 3} + {2 + 2, 5}").getValue(context, List.class);

一个操作符重载器不会改变一个操作符的默认语义。例如,在上述例子中 2+2 仍然计算结果为 4。

3.6 类型

可以使用特殊的 T 操作符来指定一个Java类的实例。静态方法也通过使用这个操作符来调用。如果使用StandardEvaluationContext,那么 java.lang 包内的类型的 T()引用不需要是写完整的包名,但所有其他类型引用必须写完整。

Class dateClass = parser.parseExpression("T(java.util.Date)").getValue(Class.class);

Class stringClass = parser.parseExpression("T(String)").getValue(Class.class);

boolean trueValue = parser.parseExpression(
		"T(java.math.RoundingMode).CEILING < T(java.math.RoundingMode).FLOOR")
		.getValue(Boolean.class);

如果使用自定义EvaluationContext,则需要手动配置一个带有特定ClassLoader的StandardTypeLocator,以确保 SpEL 表达式解析器能够定位用户类型。
例如,spring-context模块中的StandardBeanExpressionResolver使用相应BeanFactory的 beanClassLoader来配置StandardTypeLocator。

3.7 对象构造

需要构造对象的时候,需要用 new 关键字并且要写完整的包名+类名 (除了java.lang包)

Inventor einstein = p.parseExpression(
		"new org.spring.samples.spel.inventor.Inventor('Albert Einstein', 'German')")
		.getValue(Inventor.class);

3.8 变量

在EvaluationContext 中使用setVariable()方法设置变量,在表达式中使用#变量名来获取变量的值, 变量名的命名规范遵循Java语言变量名的命名规范。

Inventor tesla = new Inventor("Nikola Tesla", "Serbian");

EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();
context.setVariable("newName", "Mike Tesla");

parser.parseExpression("name = #newName").getValue(context, tesla);
System.out.println(tesla.getName());  // "Mike Tesla"

有特殊的两个变量 #this和#root,#this变量总是被定义并且指代当前正在评估的对象。#root变量总是被定义并且指代根上下文对象。

// Create a list of prime integers.
List<Integer> primes = List.of(2, 3, 5, 7, 11, 13, 17);

// Create parser and set variable 'primes' as the list of integers.
ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();
context.setVariable("primes", primes);

// Select all prime numbers > 10 from the list (using selection ?{...}).
String expression = "#primes.?[#this > 10]";

// Evaluates to a list containing [11, 13, 17].
List<Integer> primesGreaterThanTen =
		parser.parseExpression(expression).getValue(context, List.class);

#this和#root共用:

// Create parser and evaluation context.
ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();

// Create an inventor to use as the root context object.
Inventor tesla = new Inventor("Nikola Tesla");
tesla.setInventions("Telephone repeater", "Tesla coil transformer");

// Iterate over all inventions of the Inventor referenced as the #root
// object, and generate a list of strings whose contents take the form
// "<inventor's name> invented the <invention>." (using projection !{...}).
String expression = "#root.inventions.![#root.name + ' invented the ' + #this + '.']";

// Evaluates to a list containing:
// "Nikola Tesla invented the Telephone repeater."
// "Nikola Tesla invented the Tesla coil transformer."
List<String> results = parser.parseExpression(expression)
		.getValue(context, tesla, List.class);

3.9 方法

通过注册用户定义的函数来扩展 SpEL,这些函数可以在表达式中通过使用#functionName(…)语法来调用。函数可以通过setVariable()方法在EvaluationContext实现中作为变量进行注册。
StandardEvaluationContext还定义了registerFunction(…)方法,这些方法提供了一种方便的方式来将一个函数注册为java.lang.reflect.Method或java.lang.invoke.MethodHandle。

注册一个Mehtod:

public abstract class StringUtils {

	public static String reverseString(String input) {
		return new StringBuilder(input).reverse().toString();
	}
}

ExpressionParser parser = new SpelExpressionParser();

EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
context.setVariable("reverseString",
		StringUtils.class.getMethod("reverseString", String.class));

// evaluates to "olleh"
String helloWorldReversed = parser.parseExpression(
		"#reverseString('hello')").getValue(context, String.class);

注册一个MethodHandle:

ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();

MethodHandle mh = MethodHandles.lookup().findVirtual(String.class, "formatted",
		MethodType.methodType(String.class, Object[].class));
context.setVariable("message", mh);

// evaluates to "Simple message: <Hello World>"
String message = parser.parseExpression("#message('Simple message: <%s>', 'Hello World', 'ignored')")
		.getValue(context, String.class);

如果目标和所有的参数都被绑定,这很可能会有更好的性能。在那种情况下,在 SpEL 表达式中不需要任何参数

ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();

String template = "This is a %s message with %s words: <%s>";
Object varargs = new Object[] { "prerecorded", 3, "Oh Hello World!", "ignored" };
MethodHandle mh = MethodHandles.lookup().findVirtual(String.class, "formatted",
		MethodType.methodType(String.class, Object[].class))
		.bindTo(template)
		.bindTo(varargs); //here we have to provide arguments in a single array binding
context.setVariable("message", mh);

// evaluates to "This is a prerecorded message with 3 words: <Oh Hello World!>"
String message = parser.parseExpression("#message()")
		.getValue(context, String.class);

3.10 Bean参照

如果上下文已经使用一个 Bean 解析器进行了配置,你可以通过使用@符号从表达式中查找 beans。

ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setBeanResolver(new MyBeanResolver());

// This will end up calling resolve(context,"something") on MyBeanResolver during evaluation
Object bean = parser.parseExpression("@something").getValue(context);

要访问工厂 bean 本身,应该在 bean 名称前加上一个&符号

ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setBeanResolver(new MyBeanResolver());

// This will end up calling resolve(context,"&foo") on MyBeanResolver during evaluation
Object bean = parser.parseExpression("&foo").getValue(context);

4 模板表达式

模板表达式允许将字面文本与一个或多个求值块混合。每个求值块用你可以定义的前缀和后缀字符来界定。一个常见的选择是使用#{ }作为界定符。

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

// evaluates to "random number is 0.7038186818312008"

TemplateParserContext 是ParserContext接口的实现类,定义了用#{ }包裹SpEL内容。

Spring系列第39篇:强大的Spel表达式 JVM,JAVA集合,JAVA多线程并发,JAVA基础,Spring原理,微服务,Netty与RPC,网络,日志,Zookeeper,Kafka,RabbitMQ,Hbase,MongoDB,Cassandra,设计模式,负载均衡,数据库,一致性哈希,JAVA算法,数据结构,加密算法,分布式缓存,Hadoop,Spark,Storm,YARN,机器学习,云计算…《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门即可获取!属性其实是获取容器中的Bean。 阅读详情

相关推荐

Spring SpEL 表达式语言

Spring也有自己的EL,叫Spring Expression Language,简称SpEl。其可以在程序中单独使用,也可以在Spring应用中进行bean定义时使用。其核心是org.springframework.expression.Expression接口,Spring使用该接口来表示EL中的表达式。通过Expression接口的系列getValue()方法我们可以获取对应Expression在特定EvaluationContext下的值,也可以通过其系列setValue()方法来设值。

REID丶Beginner的博客 1912

SpEL表达式详解

`Spring Expression Language`(简称SpEL)是一种功能强大的表达式语言,是`spring`提供的,该语言类似于JSP当中的EL表达式。但提供了很多额外的功能,最出色的就是`函数调用`和`简单字符串的模板函数`。他需要使用`spring`提供的解析器来解析,但是他不依赖于`spring`,可以独立使用。在`spring`程序当中,我们不用管解析器,由`spring`来帮我们自动构建。我们只需要写想要表达的字符串,交给`spring`来进行解析即可。

怪咖@的博客 3万+

SpringSecurity方法安全:@PreAuthorize与SpEL表达式

方法级安全是Spring Security的核心特性之一,它允许开发者在方法执行前、执行后甚至执行过程中应用安全控制。与基于URL的安全控制相比,方法级安全提供了更细粒度的访问控制机制,特别适合复杂业务场景下的权限管理需求。方法级安全可以基于用户角色、权限、方法参数甚至是返回值进行控制,使得安全规则能够与业务逻辑紧密结合。要启用Spring Security的方法级安全,需要在配置类上添加@EnableMethodSecurity注解。

程序媛学姐的博客 1928

Spring系列19:SpEL详解

本文内容 SpEL概念 快速入门 关键接口 全面用法 bean定义中使用 SpEL概念 Spring 表达式语言(简称“SpEL”)是一种强大的表达式语言,支持在运行时查询和操作对象图。语言语法类似于 Unified EL,但提供了额外的功能,最值得注意的是方法调用和基本的字符串模板功能。 虽然 SpEL 是 Spring 产品组合中表达式评估的基础,但它不直接与 Spring 绑定,可以独立使用。 表达式语言支持以下功能: 字面表达式 布尔和关系运算符 正则表达式 类表达式 访问属性、数组

qq_21579619的博客 2万+

Spring MVC 根据 controller 层方法入参和返回值动态生成日志 - 下 :借助 SpEL 或自定义的方式解析日志表达式

上一篇文章已经就如何获取到 controller 层方法的参数和返回值进行了详细分析,并且封装了 HandlerMethodPostProcessor 接口以便使用,接下来就实现业务需求:根据 controller 层方法的入参和返回值动态生成日志。 实现日志解析 实现思路是这样的:定义一个注解,注解的 value 为日志表达式,HandlerMethodPostProcessor#postPro...

Duan的博客 1071

大模型训练和推理

大模型训练moe是指混合专家(Mixture-of-experts,简称MoE)的,这是一种用于提高大型神经网络性能的技术,它可以将模型的一部分替换为多个专家,每个专家只负责处理一部分输入数据,从而增加模型的参数量和表达能力,同时减少计算量和训练时间。指令可以作为模型的输入的一部分,也可以作为模型的输出的一部分,具体取决于任务的类型。上下文扩展技术的,这是一种用于提高大型语言模型(LLM)对长文本的处理能力的技术,它可以让模型在不增加参数量的情况下,扩展其注意力范围,从而提高模型的语言理解和生成能力。

weixin_45325331的博客 6052

从头认识Spring-1.14 SpEl表达式(3)-SpEl表达式的两个坑:Bean的顺序与Bean的toString方法

这一章节我们来说一下SpEl表达式的坑,以及补充一下SpEl表达式操作类的方法与常量。1.domain厨师类:(新增一个朋友属性)package com.raylee.my_new_spring.my_new_spring.ch01.topic_1_16; public class Chief { private String name = ""; private Oven oven;

raylee2007的专栏 4710

深度伪造检测实战:轻量级频域特征 pipeline 部署指南

深度伪造检测(deepfake detection)是多媒体内容安全的核心技术,其本质是通过建模生成式篡改在像素与频域留下的微弱异常痕迹。传统端到端大模型虽在标准数据集上表现优异,却因训练域与真实场景失配、计算开销高、缺乏可解释性而难以落地。本文聚焦于工程可复现的实践路径,提出‘人脸定位→频域伪造特征提取(Xception-FCN + Frequency-Aware Masking)→轻量分类决策’三段式解耦架构,兼顾精度、延迟与可解释性。该方案已在边缘设备(Jetson Orin NX)实现单帧<48ms

weixin_33437929的博客 316

自定义注解中使用SpEL表达式,动态获取方法参数或执行方法

获取变量的功能,比较常见的用法是spring中缓存注解的功能。可以动态获取方法中参数的值。如下: 1.2 执行方法 这个例子用过spring security的或者类似的授权框架的可能比较熟悉。如下 这里其实就是通过表达式去执行某个类的hasRole方法,参数为’ROLE_ADMIN’,然后获得返回值再进行后续操作。表达式不仅支持获取属性和执行方法,还支持各种运算符操作,能查到很多其他大神写的。这里就不写了写demo之前先简单介绍一下执行表达式时比较重要的几个类 最后获得的value就是传入的值,这个dem

weixin_42645678的博客 1万+

自动驾驶仿真 (三)—— 基于PreScan与Simulink的AEB系统仿真

自动驾驶仿真三—— 基于PreScan&Simulink的AEB系统仿真1. AEB自动紧急制动系统1. 1 TTC碰撞时间模型1. 2 C-NCAP法规部分术语与定义1. 3 主动安全ADAS系统试验项目2. AEB仿真分析建模2.1 搭建场景2.2 传感器建模2.3 添加AEB控制系统3. 典型工况仿真3.1 CCRs仿真测试3.1 CCRm仿真测试4. 参考学习的书目教材 博主前面的博文已经介绍了Prescan&Simulink基本的场景建模及仿真分析流程,《自动驾驶仿真 (二)——

zhudj08的博客 1万+

别再踩坑了!保姆级教程:用Arduino IDE 2 + STM32Duino搞定STM32开发环境(附ST-Link驱动和CubeProgrammer配置)

本文提供了一份详细的STM32开发环境搭建教程,使用Arduino IDE 2和STM32Duino,涵盖从安装配置到烧录实战的全过程。文章特别针对ST-Link驱动安装和STM32CubeProgrammer配置中的常见问题提供了解决方案,帮助开发者快速搭建稳定的开发环境并避免常见陷阱。

weixin_34188805的博客 386

自定义注解,通过SpEL表达式调用类方法、引用方法参数、引用方法参数的属性

*** 数据编号* @return*//*** API提供商*//*** API功能*//*** API调用场景*//*** API响应码* 通过该名称获取响应code值,判断API是否响应成功*//*** API响应码值* API响应码值,一般填成功的码值*/注解的属性随意,按照功能需求设计。

weixin_46228563的博客 558

VirtualBox虚拟机上ubuntu系统安装问题记:显示画面太小、启动就异常退出等

报错:Failed to load R0 module D:/VMMR0.r0: The path is not clean of leading double slashes: ‘D:/VMMR0.r0’ (VERR_SUPLIB_PATH_NOT_CLEAN).解决方法特别简单,就是安装VIrtualBox的时候不要安装在CDE等盘根目录下。首先VirtualBox的下载安装过程是比较简单的,此处就不赘述了。然后E盘下新建个目录,安装到这个目录下就可解决。

qq_42595610的博客 2833

Spring判断方法名是符合给定的SPEL+表达式的+API

我们先使用SpelExpressionParser类来解析表达式,然后再创建一个StandardEvaluationContext对象,并将方法名作为变量设置到上下文中。最后,我们使用parseExpression方法来解析表达式,并使用getValue方法来获取表达式的结果。在此例子中,我们的表达式为#methodName.matches(‘get.*ById’),它将检查方法名是否以"get"开头,并以"Id"结尾。再分享我整理汇总的一些 Java 面试相关资料(亲自验证,严谨科学!

JavaEdge全是干货的技术号 1058

C# ScottPlot 5.0 WinForms 十字光标示例:轻松实现动态数值显示,你学会了吗?

ScottPlot是一个免费、开源的.NET交互式绘图库,能够轻松地实现大型数据集的交互式显示。它支持多种图表类型,如折线图、柱状图、饼图、散点图等。ScottPlot的性能非常出色,即使是处理千万级别的数据也游刃有余。

java专栏 2231

分享6款文字语音生成驱动虚拟数字人说话的开源项目

对定性和定量结果的大量实验表明,我们的算法实现了高质量的照片真实感对话头部视频,包括根据语音节奏进行的各种面部表情和头部运动,并超过了最先进的水平。我们的系统包含三个阶段。当然,FACEGOOD Audio2face 部分也可根据自己的喜好进行重新训练,比如你想用自己的声音或其它类型的声音,或者不同于 FACEGOOD 使用的模型绑定作为驱动数据,都可以根据下面提到的流程完成自己专属的动画驱动算法模型训练。兼顾生成的韵律和外表的相似,除了面部,考虑到了头部的动作,虑了背景区域的artifact。

南七小僧的学海无涯 3057

动态限流新范式:Resilience4j方法级SpEL表达式实战指南

你是否还在为固定限流参数无法应对业务波动而烦恼?当促销活动突然带来10倍流量时,静态配置的限流规则是否让系统陷入"一刀切"的尴尬?本文将带你掌握Resilience4j的SpEL(Spring表达式语言)动态参数能力,通过方法级别的精细化控制,让限流策略真正适配业务场景变化。读完本文你将获得: - 理解SpEL表达式如何赋能限流参数动态化 - 掌握3种核心限流参数的动态配置技巧 - 学会在Spri...

gitblog_00949的博客 510

Plant Simulation 双深位立库开发系列教程-货架参数化

为了方便用户进行货架参数化,我们需要在交互界面上进行参数调整,右键打开RackLane,打开Dialog,在Rack_tab的tab下创建相应的对象,并创建NumberOfRightRack和NumberOfLeftRack作为数据连接对象。通过Rack._3D.VisibleGraphicGroups := ["default"]来切换需要显示的Rack,当不需要显示则可以Rack._3D.VisibleGraphicGroups := [""]即可。首先,加载默认的HBW库到模型中,确保结构树当中有。

santayana的专栏 1264

[034][公共模块]基于SpEL的方法参数表达式求值器设计与实现

摘要 本文设计实现了一个基于SpEL的方法参数表达式求值器,用于在Spring应用中进行动态表达式计算。该组件支持方法上下文感知、占位符解析、Bean引用、自定义变量注入等功能,通过优雅的接口设计和缓存机制提高性能。实现类SpelMethodBasedExpressionEvaluator利用Spring的SpEL引擎,将方法参数、Bean容器等无缝暴露给表达式,提供类型安全的求值结果。文章详细解析了核心功能、接口设计、实现细节及使用示例,展示了该组件在权限控制、缓存等场景的应用价值。

杨运交的博客 239

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

spring之Bean 的作用域、使用外部属性文件、表达式语言SpEL、Bean 的生命周期方法

1、Bean 的作用域 在 Spring 中, 可以在 元素的 scope 属性里设置 Bean 的作用域. 默认情况下, Spring 只为每个在 IOC 容器里声明的 Bean 创建唯一一个实例, 整个 IOC 容器范围内都能共享该实例:所有后续的 getBean() 调用和 Bean 引用都将返回这个唯一的 Bean 实例.该作用域被称为 singleton, 它是所有 B...

qq_34983808的博客 239

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

用SPEL表达式快速验证业务规则的3种方法

在实际开发中,我们经常需要处理各种业务规则验证,比如折扣计算、风控策略等。不需要搭建本地环境,打开网页就能直接测试SPEL表达式,还能一键保存测试用例,非常方便。如果你也经常需要处理业务规则验证,不妨试试SPEL表达式这个方案,配合合适的工具平台,真的能让开发效率提升不少。编写完成后可以立即执行查看结果。SPEL支持设置安全上下文,限制可访问的类和方法,确保表达式执行安全。通过自定义函数和方法,可以扩展SPEL的能力,支持更复杂的业务逻辑。不仅显示最终结果,还会展示表达式的解析过程,方便调试复杂逻辑。

AmberLeopard26的博客 112

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

spring之SpEL表达式

1.什么是SpEL表达式 SpEL表达式语言是一种表达式语言,是一种可以与一个基于spring的应用程序中的运行时对象交互的东西。有点类似于ognl表达式。总得来说SpEL表达式是一种简化开发的表达式,通过使用表达式来简化开发,减少一些逻辑、配置的编写。 2.使用XML方式实现SpEL表达式

sunpy 6万+

Resilience4j方法参数SpEL表达式:动态配置熔断名称

在微服务架构中,熔断器(Circuit Breaker)是保障系统稳定性的关键组件。传统静态配置方式存在显著局限性: - 固定熔断名称无法区分同一接口的不同业务场景 - 多租户系统中难以实现隔离的熔断策略 - 动态调整熔断粒度需大量冗余代码 Resilience4j作为Java生态主流的容错库,通过Spring Expression Language(SpEL表达式)提供了动态参数配置能力,允许...

gitblog_00961的博客 751

【Spring应用】SPEL表达式使用

Spring框架中的SpEL(Spring Expression Language,Spring表达式语言)是一种基于字符串的表达式语言,用于支持在运行时动态地计算表达式的值。它可以在Spring的多个模块中使用,如Spring MVC、Spring Security等,是Spring框架中一个重要的特性。SpEL表达式的解析和计算是在运行时动态进行的,因此具有很大的灵活性和可扩展性,可以在不改变代码的情况下实现复杂的运算和逻辑判断。这个表达式表示对2和3进行加法运算,其结果为5。

qq_43783527的博客 1130

Spring系列之强大的Spel表达式

本文带你玩转spring中强大的spel表达式! Spel概述 Spring表达式语言全称为“Spring Expression Language”,缩写为“SpEL”,类似于Struts2x中使用的OGNL表达式语言,能在运行时构建复杂表达式、存取对象图属性、对象方法调用等等,并且能与Spring功能完美整合,如能用来配置Bean定义。 表达式语言给静态Java语言增加了动态功能。 SpEL是单独模块,只依赖于core模块,不依赖于其他模块,可以单独使用。 Spel能干什么? 表达式语言一般是

azhou的代码园 6719
上一篇: SpringBoot读取指定yaml文件内容
下一篇: SpringBoot各类数量限制及超出后抛出的异常
118路司机
博客等级 码龄9年 6929粉丝 153原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值