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

4
在升级到Spring 3之前,我的applicationContext.xml文件中有以下内容:
    <bean class="com.northgateis.pole.ws.PolePayloadValidatingInterceptor">
      <property name="validateRequest" value="${validateRequest}" />
      <property name="validateResponse" value="${validateResponse}" />
    </bean>

${validateRequest}和${validatePayload}是可能在我的属性文件中定义或未定义的属性。

在Spring 2中,如果这些属性在属性文件中不存在,则不会调用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运算符后面的值总是被使用,即使属性在属性文件中已经定义。有趣的是这种语法是可接受的。

有什么建议吗?

2个回答

6

看起来Spring 3在使用Elvis运算符处理默认值时存在一些问题。显然这个问题已经在最新的Spring 3.0.3中得到了修复(请参见SPR-7209),正确的语法应该是相当复杂的:

#{${validateRequest}?:true}

2
看起来很有希望。当属性为null(即在属性文件中为空)时,确实可以工作,但如果属性在属性文件中不存在,则会导致相同的“Could not resolve placeholder 'validateRequest'”BeanDefinitionStoreException。我将尝试重新打开SPR-7209,并查看Spring团队是否愿意将缺失视为等效于空白。 - David Easley

3

在使用占位符配置器解析时,没有必要使用Spring EL来设置缺失属性的默认值。只需使用${validateRequest:true}即可。"Elvis操作符"并不涉及解析占位符,它只依赖于占位符配置器提供的任何输入。

请参见SPR-4785


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接