2010-06-16 50 views
4

之前升級到春天3我在applicationContext.xml文件有這樣的:我可以在Spring EL中使用屬性佔位符嗎?

<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中硬編碼的默認值。

升級到春天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> 

即使在proeprties文件中定義屬性時,總是使用Elvis操作符後的值。有趣的是,語法被接受。

有什麼建議嗎?

回答

6

看起來Spring 3對Elvis操作符默認值的處理相當破裂。這顯然已經固定的(見SPR-7209)在新鮮外的的烤箱春天3.0.3,和正確的語法應該是相當巴洛克:

#{${validateRequest}?:true} 
+2

看起來很有希望。當屬性爲空(即在屬性文件中爲空)時,這確實有效,但會導致相同的「無法解析佔位符validateRequest」「BeanDefinitionStoreException,如果該屬性不在屬性文件中。我會嘗試重新打開SPR-7209,看看春季隊是否會允許缺席被視爲等同於空白。 – 2010-06-17 09:02:25

3

沒有必要爲Spring EL設置使用佔位符配置器解析缺失屬性時的默認值。只需使用${validateRequest:true}即可。 「Elvis操作符」不涉及解析佔位符,它只依賴佔位符配置器提供的任何輸入。

參見SPR-4785