2014-03-12 63 views
0

我想要獲取屬性的值在Environment上下文中與環境bean配置(如在spring PropertyPlaceholderConfigurer and context:property-placeholder選中的答案)。從彈簧中獲取配置的屬性

public class SpringsPropertiesProvider implements IPropertiesProvider { 
    @Autowired Environment envinronment; 

    @Override 
    public String getProperty(String key) { 
     return envinronment.getProperty(key); 
    } 

} 

此類註冊與下面的XML:

<context:property-placeholder 
    location="classpath:myproject/example.properties" /> 
<context:annotation-config /> 
<bean class="myproject.SpringsPropertiesProvider" id="springsPropertiesProvider"/> 

但SpringsPropertiesProvider.getProperty方法不返回example.properties文件中配置的值。

我在做什麼錯了,我該如何獲得由placeholderconfigurer配置的屬性的動態訪問?

PS。 在environment.getPropert(key)調用過程中,顯示​​org.springframework.core.env.PropertySourcesPropertyResolver在其propertySources字段([systemProperties,systemEnvironment])中只有兩個條目,並且這兩個條目都不包含任何在example.properties中定義的鍵。

回答

1

試試這個

<context:property-placeholder 
    location="classpath:myproject/example.properties" ignore-resource-not-found="true"/> 

如果該項目不那麼啓動,這意味着春天無法找到屬性文件。說到這些,你的項目結構是什麼樣子的?

更新:

以下link解釋了爲什麼這不工作

+0

Geoand謝謝。我幾乎按照你的建議檢查了這一點 - 通過使文件路徑不正確,因此上下文加載失敗 - 所以原始路徑設置是正確的。 –

+0

如果使用@Value(「$ {nameOfProperty})注入屬性,會發生什麼? – geoand

+0

剛剛檢查 - 正在處理這個。 –