我可以使用Spring EL的属性占位符吗?

时间:2010-06-16 17:09:47

标签: spring spring-el

在升级到Spring 3之前,我在applicationContext.xml文件中有这个:

    <bean class="com.northgateis.pole.ws.PolePayloadValidatingInterceptor">
      <property name="validateRequest" value="${validateRequest}" />
      <property name="validateResponse" value="${validateResponse}" />
    </bean>

其中$ {validateRequest)和$ {validateRequest)引用可能在我的属性文件中定义的属性。

在Spring 2中,如果属性文件中没有这些proeprties,则不会调用bean上的setter,因此使用了PolePayloadValidatingInterceptor中的硬编码默认值。

升级到Spring 3后,行为似乎不同:如果属性文件中没有属性,我会得到以下异常:

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'annotationMapping' defined in class path resource [com/northgateis/pole/ws/applicationContext-ws.xml]: Could not resolve placeholder 'validateRequest'
 at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:272)
 at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:75)
 at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:640)
 at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:615)
 at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:405)
 at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:272)

我尝试使用Spring EL,但以下似乎不起作用:

    <bean class="com.northgateis.pole.ws.PolePayloadValidatingInterceptor">
      <property name="validateRequest" value="${validateRequest?:true}" />
      <property name="validateResponse" value="${validateResponse?:false}" />
    </bean>

始终使用Elvis运算符后的值,即使在proeprties文件中定义了属性也是如此。有趣的是语法被接受了。

有什么建议吗?

2 个答案:

答案 0 :(得分:6)

看起来Spring 3对Elvis运算符的默认值的处理相当破碎。这显然已经在新鲜出炉的Spring 3.0.3中修复了(参见SPR-7209),正确的语法应该是相当巴洛克式的:

#{${validateRequest}?:true}

答案 1 :(得分:3)

使用占位符配置器解析时,Spring EL不需要为缺失属性设置默认值。只需使用${validateRequest:true}即可。 “Elvis运算符”不关心解析占位符,它只依赖于占位符配置器提供的任何输入。

请参阅SPR-4785

相关问题