1、介绍
Spring Expression Language(简称 SpEL)是一种功能强大的表达式语言,支持运行时查询和操作对象图
2、用法
2.1 注解@Value中
2.2 XML配置
2.3 代码中使用Expression
3、表达式(目前用到两种)
3.1 类类型表达式
3.1.1 释义
使用“T(Type)”来表示java.lang.Class实例,“Type”必须是类全限定名,“java.lang”包除外,即该包下的类可以不指定包名;使用类类型表达式还可以进行访问类静态方法及类静态字段。
3.1.2 示例
@SpringBootTest
public class Test01 {
public static int sub(int x, int y){
return x - y;
}
@Test
void test() {
StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
evaluationContext.setBeanResolver(new SpelBeanResolver());
ExpressionParser expressionParser = new SpelExpressionParser();
Expression expression = expressionParser.parseExpression(
"T(com.xingyu.Test01).sub('1','5')");
Object value = expression.getValue(evaluationContext);
System.out.println(value);
}
}
3.2 @beanName
3.2.1 释义
在SPEL表达式中访问springbean,需要通过StandardEvaluationContext来设置对应的BeanResolver,同时我们需要在SPEL表达式以@beanName的方法来访问对应的bean对象
3.2.2 示例
@SpringBootTest
public class Test01 {
@Test
void test() {
StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
evaluationContext.setBeanResolver(new SpelBeanResolver());
ExpressionParser expressionParser = new SpelExpressionParser();
Expression expression = expressionParser.parseExpression(
"@testController.sum('1','5')");
Object value = expression.getValue(evaluationContext);
System.out.println(value);
}
}
@Component
public class SpelBeanResolver implements BeanResolver, ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
@Override
public Object resolve(EvaluationContext context, String beanName) throws AccessException {
return applicationContext.getBean(beanName);
}
}
@RestController(value = "testController")
@RequestMapping
@Slf4j
public class TestController {
public static int sum(int x, int y) {
log.info("sum start, x = {}, y={}", x, y);
int res = x + y;
log.info("sum end");
return res;
}
}