---
title: "【第五章】Spring表达式语言 之 5.4在Bean定义中使用EL—跟我学spring3"
author: "maakey"
date: "2012-02-23T12:12:00Z"
tags: []
slug: "spring-5-4-bean-el-spring3"
draft: false
lastmod: "2012-12-23T23:06:13Z"
id: 1752716
url: "https://maakey.iteye.com/blog/1752716"
---

### 5.4.1 xml风格的配置

SpEL支持在Bean定义时注入，默认使用“#{SpEL表达式}”表示，其中“#root”根对象默认可以认为是ApplicationContext，只有ApplicationContext实现默认支持SpEL，获取根对象属性其实是获取容器中的Bean。

首先看下配置方式（chapter5/el1.xml）吧：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2464.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2464.html)[打印](http://sishuok.com/forum/blogPost/list/2464.html)

01. &lt;beanid="world"class="java.lang.String"&gt;
02. &lt;constructor-argvalue="#{'World!'}"/&gt;
03. &lt;/bean&gt;
04. &lt;beanid="hello1"class="java.lang.String"&gt;
05. &lt;constructor-argvalue="#{'Hello'}#{world}"/&gt;
06. &lt;/bean&gt;
07. &lt;beanid="hello2"class="java.lang.String"&gt;
08. &lt;constructor-argvalue="#{'Hello'+world}"/&gt;
09. &lt;!--不支持嵌套的--&gt;
10. &lt;!--&lt;constructor-argvalue="#{'Hello'#{world}}"/&gt;--&gt;
11. &lt;/bean&gt;
12. &lt;beanid="hello3"class="java.lang.String"&gt;
13. &lt;constructor-argvalue="#{'Hello'+@world}"/&gt;
14. &lt;/bean&gt;

模板默认以前缀“#{”开头，以后缀“}”结尾，且不允许嵌套，如“#{'Hello'#{world}}”错误，如“#{'Hello' + world}”中“world”默认解析为Bean。当然可以使用“@bean”引用了。

接下来测试一下吧：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2464.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2464.html)[打印](http://sishuok.com/forum/blogPost/list/2464.html)

01. @Test
02. publicvoidtestXmlExpression(){
03. ApplicationContextctx=newClassPathXmlApplicationContext("chapter5/el1.xml");
04. Stringhello1=ctx.getBean("hello1",String.class);
05. Stringhello2=ctx.getBean("hello2",String.class);
06. Stringhello3=ctx.getBean("hello3",String.class);
07. Assert.assertEquals("HelloWorld!",hello1);
08. Assert.assertEquals("HelloWorld!",hello2);
09. Assert.assertEquals("HelloWorld!",hello3);
10. }

是不是很简单，除了XML配置方式，Spring还提供一种注解方式@Value，接着往下看吧。

### 5.4.2 注解风格的配置

基于注解风格的SpEL配置也非常简单，使用@Value注解来指定SpEL表达式，该注解可以放到字段、方法及方法参数上。

测试Bean类如下，使用@Value来指定SpEL表达式：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2464.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2464.html)[打印](http://sishuok.com/forum/blogPost/list/2464.html)

1. packagecn.javass.spring.chapter5;
2. importorg.springframework.beans.factory.annotation.Value;
3. publicclassSpELBean{
4. @Value("#{'Hello'+world}")
5. privateStringvalue;
6. //setter和getter由于篇幅省略，自己写上
7. }

首先看下配置文件(chapter5/el2.xml)：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2464.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2464.html)[打印](http://sishuok.com/forum/blogPost/list/2464.html)

01. &lt;?xmlversion="1.0"encoding="UTF-8"?&gt;
02. &lt;beansxmlns="http://www.springframework.org/schema/beans"
03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04. xmlns:context="http://www.springframework.org/schema/context"
05. xsi:schemaLocation="
06. http://www.springframework.org/schema/beans
07. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
08. http://www.springframework.org/schema/context
09. http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt;
10. &lt;context:annotation-config/&gt;
11. &lt;beanid="world"class="java.lang.String"&gt;
12. &lt;constructor-argvalue="#{'World!'}"/&gt;
13. &lt;/bean&gt;
14. &lt;beanid="helloBean1"class="cn.javass.spring.chapter5.SpELBean"/&gt;
15. &lt;beanid="helloBean2"class="cn.javass.spring.chapter5.SpELBean"&gt;
16. &lt;propertyname="value"value="haha"/&gt;
17. &lt;/bean&gt;
18. &lt;/beans&gt;

配置时必须使用“&lt;context:annotation-config/&gt;”来开启对注解的支持。

有了配置文件那开始测试吧：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2464.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2464.html)[打印](http://sishuok.com/forum/blogPost/list/2464.html)

1. @Test
2. publicvoidtestAnnotationExpression(){
3. ApplicationContextctx=newClassPathXmlApplicationContext("chapter5/el2.xml");
4. SpELBeanhelloBean1=ctx.getBean("helloBean1",SpELBean.class);
5. Assert.assertEquals("HelloWorld!",helloBean1.getValue());
6. SpELBeanhelloBean2=ctx.getBean("helloBean2",SpELBean.class);
7. Assert.assertEquals("haha",helloBean2.getValue());
8. }

其中“helloBean1 ”值是SpEL表达式的值，而“helloBean2”是通过setter注入的值，这说明setter注入将覆盖@Value的值。

### 5.4.3 在Bean定义中SpEL的问题

如果有同学问“#{我不是SpEL表达式}”不是SpEL表达式，而是公司内部的模板，想换个前缀和后缀该如何实现呢？

那我们来看下Spring如何在IoC容器内使用BeanExpressionResolver接口实现来求值SpEL表达式，那如果我们通过某种方式获取该接口实现，然后把前缀后缀修改了不就可以了。

此处我们使用BeanFactoryPostProcessor接口提供postProcessBeanFactory回调方法，它是在IoC容器创建好但还未进行任何Bean初始化时被ApplicationContext实现调用，因此在这个阶段把SpEL前缀及后缀修改掉是安全的，具体代码如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2464.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2464.html)[打印](http://sishuok.com/forum/blogPost/list/2464.html)

01. packagecn.javass.spring.chapter5;
02. importorg.springframework.beans.BeansException;
03. importorg.springframework.beans.factory.config.BeanFactoryPostProcessor;
04. importorg.springframework.beans.factory.config.ConfigurableListableBeanFactory;
05. importorg.springframework.context.expression.StandardBeanExpressionResolver;
06. publicclassSpELBeanFactoryPostProcessorimplementsBeanFactoryPostProcessor{
07. @Override
08. publicvoidpostProcessBeanFactory(ConfigurableListableBeanFactorybeanFactory)
09. throwsBeansException{
10. StandardBeanExpressionResolverresolver=(StandardBeanExpressionResolver)beanFactory.getBeanExpressionResolver();
11. resolver.setExpressionPrefix("%{");
12. resolver.setExpressionSuffix("}");
13. }
14. }

首先通过 ConfigurableListableBeanFactory的getBeanExpressionResolver方法获取BeanExpressionResolver实现，其次强制类型转换为StandardBeanExpressionResolver，其为Spring默认实现，然后改掉前缀及后缀。

开始测试吧，首先准备配置文件(chapter5/el3.xml)：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2464.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2464.html)[打印](http://sishuok.com/forum/blogPost/list/2464.html)

01. &lt;?xmlversion="1.0"encoding="UTF-8"?&gt;
02. &lt;beansxmlns="http://www.springframework.org/schema/beans"
03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04. xmlns:context="http://www.springframework.org/schema/context"
05. xsi:schemaLocation="
06. http://www.springframework.org/schema/beans
07. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
08. http://www.springframework.org/schema/context
09. http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt;
10. &lt;context:annotation-config/&gt;
11. &lt;beanclass="cn.javass.spring.chapter5.SpELBeanFactoryPostProcessor"/&gt;
12. &lt;beanid="world"class="java.lang.String"&gt;
13. &lt;constructor-argvalue="%{'World!'}"/&gt;
14. &lt;/bean&gt;
15. &lt;beanid="helloBean1"class="cn.javass.spring.chapter5.SpELBean"/&gt;
16. &lt;beanid="helloBean2"class="cn.javass.spring.chapter5.SpELBean"&gt;
17. &lt;propertyname="value"value="%{'Hello'+world}"/&gt;
18. &lt;/bean&gt;
19. &lt;/beans&gt;

配置文件和注解风格的几乎一样，只有SpEL表达式前缀变为“%{”了，并且注册了“cn.javass.spring.chapter5.SpELBeanFactoryPostProcessor”Bean，用于修改前缀和后缀的。

写测试代码测试一下吧：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2464.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2464.html)[打印](http://sishuok.com/forum/blogPost/list/2464.html)

1. @Test
2. publicvoidtestPrefixExpression(){
3. ApplicationContextctx=newClassPathXmlApplicationContext("chapter5/el3.xml");
4. SpELBeanhelloBean1=ctx.getBean("helloBean1",SpELBean.class);
5. Assert.assertEquals("#{'Hello'+world}",helloBean1.getValue());
6. SpELBeanhelloBean2=ctx.getBean("helloBean2",SpELBean.class);
7. Assert.assertEquals("HelloWorld!",helloBean2.getValue());
8. }

此处helloBean1 中通过@Value注入的“#{'Hello' + world}”结果还是“#{'Hello' + world}”说明不对其进行SpEL表达式求值了，而helloBean2使用“%{'Hello' + world}”注入，得到正确的“"Hello World!”。