7.12.2 Bean定义中的表达式语言支持

7.12.2 Bean定义中的表达式语言支持

SpEL的一个重要作用就是扩展Spring容器的功能,允许在Bean定义中使用SpEL。在XML配置件和注解中都可以使用SpELXML配置文件和注解中使用SpEL时,在表达式外面增加#{}包围即可

程序示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
E:\workspace_QingLiangJiJavaEEQiYeYingYongShiZhang5\SpEL_XML
└─src\
├─beans.xml
├─lee\
│ └─SpELTest.java
├─org\
│ └─crazyit\
│ └─app\
│ └─service\
│ ├─Axe.java
│ ├─impl\
│ │ ├─Author.java
│ │ └─SteelAxe.java
│ └─Person.java
└─test_zh_CN.properties

Author.java

例如,有如下Author类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package org.crazyit.app.service.impl;
import java.util.List;
import org.crazyit.app.service.Axe;
import org.crazyit.app.service.Person;
public class Author implements Person
{
private Integer id;
private String name;
private List<String> books;
private Axe axe;

// 此处省略getter和setter方法

public void useAxe()
{
System.out.println("我是"
+ name + ",正在砍柴\n" + axe.chop());
}
}

上面的Author类需要依赖注入namebooksaxe,当然,可以按照前面介绍的方式来进行配置,但如果使用SpEL,将可以对Spring配置做进一步简化

beans.xml

下面使用SpEL对这个Bean进行配置,配置代码如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<!-- 指定Spring配置文件的根元素和Schema 导入p:命名空间和util:命名空间的元素 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 使用util.properties加载指定资源文件 -->
<util:properties id="confTest"
location="classpath:test_zh_CN.properties" />
<!-- 配置setName()的参数时,在表达式中调用方法 配置setAxe()的参数时,
在表达式中创建对象 配置调用setBooks()的参数时,在表达式中访问其他Bean的属性 -->
<bean id="author" class="org.crazyit.app.service.impl.Author"
p:name="#{T(java.lang.Math).random()}"
p:axe="#{new org.crazyit.app.service.impl.SteelAxe()}"
p:books="#{ {confTest.a , confTest.b} }" />
</beans>

上面的代码就是利用SpEL进行配置的代码,使用SpEL可以在配置文件中调用方法创建对象(这种方式可以代替嵌套Bean语法)、访问其他Bean的属性……总之,SpEL支持的语法都可以在这里使用,SpEL极大地简化了Spring配置。
需要指出的是,在注解中使用SpEL与在XML中使用SpEL基本相似,关于Spring使用注解进行配置管理的内容请参考下一章的知识。