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

Dav*_*ley 4 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>
Run Code Online (Sandbox Code Playgroud)

其中$ {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)
Run Code Online (Sandbox Code Playgroud)

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

    <bean class="com.northgateis.pole.ws.PolePayloadValidatingInterceptor">
      <property name="validateRequest" value="${validateRequest?:true}" />
      <property name="validateResponse" value="${validateResponse?:false}" />
    </bean>
Run Code Online (Sandbox Code Playgroud)

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

有什么建议?

ska*_*man 6

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

#{${validateRequest}?:true}
Run Code Online (Sandbox Code Playgroud)

  • 看起来很有希望.当属性为null(即属性文件中为空)时,这确实有效,但如果属性文件中不存在该属性,则会导致相同的"无法解析占位符'validateRequest'"BeanDefinitionStoreException.我将尝试重新打开SPR-7209,看看Spring团队是否会允许缺席被视为等同于空白. (2认同)