1.SpEL概述

Spring表达式语言全称为“Spring Expression Language”,缩写为“SpEL”,类似于Struts2x中使用的OGNL表达式语言, 能在运行时构建复杂表达式、存取对象图属性、对象方法调用等等,并且能与Spring功能完美整合,如能用来配置Bean定义。

  • Spring表达式支持功能

  • 字符表达式
  • 布尔值和关系操作符
  • 正则表达式
  • 类表达式
  • 访问properties,arrays,lists,maps
  • 方法调用
  • 赋值
  • 调用构造器
  • 三元操作符
  • 变量
  • 用户自定义函数
  • 集合投影
  • 集合选择
  • 模板表达式

  • 使用Spring Expression接口进行求值

  • 使用ExpressionParser接口表示解析器,提供SpelExpressionParser默认实现;
  • 使用ExpressionParser的parseExpression来解析的表达式为Expression对象;
  • 构造上下文,准备比如变量定义等表达式需要的数据,此步骤可选,要视乎表达式是否有需要;
  • 通过Expression的getValue方法获取表达式的值



代码示例


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

  • 创建Bean管理
  • ​<bean id="numberGuess" class="org.spring.samples.NumberGuess"> <property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/> <!-- other properties --> </bean> ​
  • public static class FieldValueTestBean

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

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

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

    }
  • public class SimpleMovieLister{
    private MovieFindermovieFinder;
    private StringdefaultLocale;
    @Autowired
    public void configure(MovieFindermovieFinder,@Value("#{systemProperties['user.region']}"}StringdefaultLocale){
    this.movieFinder=movieFinder;
    this.defaultLocale=defaultLocale;
    }
    }
  • 自动装配构造器
  • SEL示例参考


DEMO1


ExpressionParser parser = new SpelExpressionParser();

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

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

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

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

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


DEMO2


class TestUser {
private String name;
public Date birthday;
Integer age;

TestUser(Integer age, Date birthday, String name) {
this.age = age;
this.birthday = birthday;
this.name = name;
}

public String getName() {
return name;
}
}

public class Main {
static public void main(String[] args) throws Exception {
try {
TestUser testUser = new TestUser(10, new Date(), "aaa");
ExpressionParser parser = new SpelExpressionParser();
String name = (String) parser.parseExpression("name").getValue(context);
System.out.println(name);
} catch (Exception e) {
e.printStackTrace();
}
}
}