Spring 3引入了一种新的表达式语言(SpEL),可以在bean定义中使用.语法本身已经很好地指定了.
不清楚的是,SpEL如何与先前版本中已存在的属性占位符语法进行交互.SpEL是否支持属性占位符,或者我是否必须结合两种机制的语法并希望它们结合起来?
让我举一个具体的例子.我想使用属性语法${x.y.z},但添加了由elvis运算符提供的"默认值"语法来处理${x.y.z}未定义的情况.
我尝试了以下语法但没有成功:
#{x.y.z?:'defaultValue'}#{${x.y.z}?:'defaultValue'}第一个给了我
在'org.springframework.beans.factory.config.BeanExpressionContext'类型的对象上找不到字段或属性'x'
这表明SpEL不承认这是一个属性占位符.
第二个语法抛出异常说占位符不被识别,所以占位符解析器是被调用,但未能如预期,因为没有定义属性.
文档没有提到这种交互,所以这样的事情是不可能的,或者它没有记录.
有人设法做到了吗?
好的,我已经为此设计了一个小型,独立的测试用例.这一切都按原样运作:
首先,bean定义:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
">
<context:property-placeholder properties-ref="myProps"/>
<util:properties id="myProps">
<prop key="x.y.z">Value A</prop>
</util:properties>
<bean id="testBean" class="test.Bean">
<!-- here is where the magic is required -->
<property name="value" value="${x.y.z}"/>
<!-- I want something like this
<property name="value" value="${a.b.c}?:'Value B'"/>
-->
</bean>
</beans>
Run Code Online (Sandbox Code Playgroud)
然后,琐碎的bean类:
包装测试;
public …Run Code Online (Sandbox Code Playgroud)