---
title: "spring3.0学习笔记二---SpEL表达式1"
author: "JAVA凌"
date: "2010-03-06T15:54:48Z"
tags: []
categories: ["企业架构"]
slug: "spring3-0-spel-1"
draft: false
lastmod: "2010-03-06T15:54:48Z"
id: 609294
url: "https://xiaoling0.iteye.com/blog/609294"
---

```
  相对来讲， java是一门静态语言。而我们今天要讲的是一门动态“语言”---SpEL。

动态语言和静态语言的最显著差别在于，举个例子，" 'Hello'.toUperCase()"这只是一个普通的字符串，差别在于能否把它编译和运行起来得到结果。就是说动态语言能把一个字符串解释成程序语句。如果还不是很明白的话没关系，看下面的SpEL例子。（接下去的我就用例子来做介绍了）

public void testSpEL1() {

//ExpressionParser是Spring3里的一个包，用来动态解释一个字符串。
  ExpressionParser parser = new SpelExpressionParser();
  Expression exp = parser.parseExpression(" 'Hello,World' ");
  System.out.println((String)exp.getValue());
 }

这里'Hello,World' 是一个字符串，解释起来还是一个字符串，所以打印结果是：Hello,World

 

第二个例子：调用方法

public void testSpEL2() {

ExpressionParser parser = new SpelExpressionParser();
Expression exp=parser.parseExpression(" 'Hello'.concat(' World!')");  //这里调用了字符串String的concat方法

//Expression exp=parser.parseExpression("newString('helloworld').toUpperCase()");

Stringmessage=(String)exp.getValue();

}

 

第三个例子：调用属性

ExpressionParser parser= new SpelExpressionParser();

Expression exp=parser.parseExpression("'HelloWorld'.bytes");  //得到字符串的byte

//Expression exp=parser.parseExpression("'HelloWorld'.bytes.length"); //得到属性的属性
byte [] bytes=(byte[])exp.getValue();

 

第四个例子：调用类中的属性（下面开始复杂起来了）

@Resource

public User user;  //注入之后，user.getName() 为 xiaoling

public void testSpEL() {

    //设“值域”，限定在u这个对象里
    EvaluationContext context = new StandardEvaluationContext(user);  
    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression("username"); //==user.getUsername()
    System.out.println((String)exp.getValue(context));  //结果：xiaoling

 }

或者用更简洁的一个方式 ：
  System.out.println((String)exp.getValue(user));
这样就不用设值域了！呵呵！

 

第五个例子：给对象中的属性设值

StandardEvaluationContext  context = new StandardEvaluationContext(user);

parser.parseExpression("username").setValue(context, "ling");

 

第六个例子：做判断

Expression exp=parser.parseExpression("name=='xiaoling' ");
boolean result=exp.getValue(context,Boolean.class);  //evaluate stotrue

打印出来，结果为true

 

看到这，可能你还是一头雾水：这算什么新特性啊，哪有什么用处！

用处就在于，SpEL把java变成“动”的了！（纯属我个人观点！！）

 

接下来，我们把SpEL用到bean.xml中去

先看个例子(例一)

<bean id="numberGuess" class="cn.ling.spel.NumberGuess">
   <property name="randomNumber" value="#{T(java.lang.Math).random()*100.0}"/>

</bean>

怎么样，可以在xml文件里面赋值了！呵呵！

value里面都用#{}来赋值。至于T(java.lang.Math)，它是指某个类，即Math这个类。

 

看这个例子(例二)：systemProperties

<property name="defaultLocale" value="#{systemProperties['user.region']}"/>

systemProperties是预定义好的，里面有很属性可以用，它就相当于java文件中的System.getProperty("user.region"),它能取出当前计算机所在的国家。

 

例三：引用xml里面的其它bean

<bean id="numberGuess" class="org.spring.samples.NumberGuess">
<property name="randomNumber" value="#{T(java.lang.Math).random()*100.0}"/>
<!--otherproperties-->
</bean>
<bean id="shapeGuess" class="org.spring.samples.ShapeGuess">
<property name="initialShapeSeed" value="#{numberGuess.randomNumber}"/>
<!--otherproperties-->
</bean>

 

SpEL还可以用在annotation中：

例一：用在属性上

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

   //set和get方法
   public void setDefaultLocale(StringdefaultLocale) {
      this.defaultLocale=defaultLocale;
   }

   public StringgetDefaultLocale(){
      returnthis.defaultLocale;
   }
}

例二：用在方法上

public static 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;
      }
//...
}

未完待续…………
```