1. 程式人生 > >Could not resolve placeholder原因分析及解決方案

Could not resolve placeholder原因分析及解決方案

1. 問題描述

   在啟動Junit跑單測載入資源配置檔案的時候遇到以下異常資訊:

 

Java程式碼 
  1. Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'activity_template_id' in string value "${activity_template_id}"
      
  2.     at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:173)  
  3.     at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:125
    )  
  4.     at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer$PlaceholderResolvingStringValueResolver.resolveStringValue(PropertyPlaceholderConfigurer.java:258)  
  5.     at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveStringValue(BeanDefinitionVisitor.java:282
    )  
  6.     at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveValue(BeanDefinitionVisitor.java:204)  
  7.     at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitPropertyValues(BeanDefinitionVisitor.java:141)  
  8.     at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitBeanDefinition(BeanDefinitionVisitor.java:82)  
  9.     at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:206)  
  10.     ... 29 more  

 

2. 問題分析

在讀取配置問題資訊的時候使用了入下方法:

 

Java程式碼 
  1. "propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"  
  2.           depends-on="genernatePropertyFile">  
  3.         "location">  
  4.             file:D:/idev/antx.properties  
  5.           
  6.   
 

那麼出現異常資訊的可能性有三種

(1)location中的屬性檔案配置錯誤

(2)location中定義的配置檔案裡面沒有對應的placeholder值

(3)第三種就比較麻煩點,可能是Spring容器的配置問題

Spring容器採用反射掃描的發現機制,在探測到Spring容器中有一個org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的Bean就會停止對剩餘PropertyPlaceholderConfigurer的掃描(Spring 3.1已經使用PropertySourcesPlaceholderConfigurer替代PropertyPlaceholderConfigurer了)。 

而這個基於名稱空間的配置,其實內部就是建立一個PropertyPlaceholderConfigurer Bean而已。換句話說,即Spring容器僅允許最多定義一個PropertyPlaceholderConfigurer(或),其餘的會被Spring忽略掉(其實Spring如果提供一個警告就好了)。 

 

3.解決方案

(1)

Java程式碼 
  1. "propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"  
  2.           depends-on="genernatePropertyFile">  
  3.         "location">  
  4.             file:D:/idev/antx.properties  
  5.           
  6.         "ignoreUnresolvablePlaceholders" value="true  
  7.   
 

(2)

Java程式碼 
  1. "classpath*:redis.properties" ignore-unresolvable="true" />  
        但是 ignore-unresolvable="true" 和 這兩個屬性值必須為true