Spring表达式语言全称为“Spring Expression Language”,缩写为“SpEL”,类似于Struts2x中使用的OGNL表达式语言, 能在运行时构建复杂表达式、存取对象图属性、对象方法调用等等,并且能与Spring功能完美整合,如能用来配置Bean定义。
代码示例
ExpressionParser parser= new SpelExpressionParser();
Expression exp=parser.parseExpression("'HelloWorld'");
String message=(String)exp.getValue();
<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; } }
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();
}
}
}