4

在升级到 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 中,如果属性文件中不存在这些属性,则不会调用 bean 上的设置器,因此使用 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 文件中定义了属性也是如此。有趣的是语法被接受。

有什么建议么?

4

2 回答 2

6

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

#{${validateRequest}?:true}
于 2010-06-16T18:12:06.317 回答
3

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

参见SPR-4785

于 2012-06-23T10:35:55.040 回答