2012-05-10 84 views
15

使用属性占位符文件,我们曾经有过的方式从classpath中的文件加载性能:如何在文件系统

<context:property-placeholder location="classpath:myConfigFile.properties" /> 

和它的工作很大。但是现在我们想要从不在类路径中的系统上的特定文件加载属性。我们希望能够动态加载文件,因此我们使用Java环境变量来填充文件。我给下面一个简单的例子:

在Java:

System.setProperty("my.prop.file", "/path/to/myConfigFile.properties"); 

在Spring XML:

<context:property-placeholder location="${my.prop.file}" /> 

我也尝试过这种方式,由于从卢西亚诺一个想法:

<context:property-placeholder properties-ref="prop" /> 

<util:properties id="prop" location="reso"/> 

<bean id="reso" class="org.springframework.core.io.FileSystemResource"> 
    <constructor-arg index="0" value="${my.prop.file}" /> 
</bean> 

我试过的一切都失败了。不管我设置my.prop.file。最大的点击包括:

<context:property-placeholder location="/path/to/myConfigFile.properties" /> 
(ClassNotFoundException: .path.to.myConfigFile.properties) 

<context:property-placeholder location="file:/path/to/myConfigFile.properties" /> 
(ClassNotFoundException: file:.path.to.myConfigFile.properties) 

<context:property-placeholder location="file:///path/to/myConfigFile.properties" /> 
(ClassNotFoundException: file:...path.to.myConfigFile.properties) 

如何使用属性占位符的位置在文件系统上而不在类路径上?我们使用Spring 3.0.5。

事实证明,运行加载弹簧文件的Java程序的脚本存在问题。感谢您的帮助。我将要求删除这个问题,毕竟原始代码是有效的。 谢谢你的帮助。

+13

BTW强烈不同意瓦特/这个被关闭 –

+1

也不同意这个结论,我在Google搜索后来到了这里,它描述了我的确切问题...... –

+1

我也是 - 我不明白为什么这个关于“过于本地化”的类别关闭了?它看起来相当普遍对我? – monojohnny

回答

4

这种情况怎么样?

<context:property-placeholder properties-ref="prop" /> 

<util:properties id="prop" location="reso"/> 

<bean id="reso" class="org.springframework.core.io.FileSystemResource"> 
    <constructor-arg index="0" value="/yourpathandfile" /> 
</bean> 
+0

我可以放入value =“/ yourpathandfile”的Java环境变量?我会给它一个镜头。谢谢 –

+0

这似乎并不奏效。该物业正在通过,但同样的错误发生。不过谢谢你的帮助。这不可能吗? –

+0

如果你用真实路径硬编码$ {my.prop.file}来查看是否有效,该怎么办? – Luciano

14

这为我所做的工作:

<context:property-placeholder location="file:/path/to/myConfigFile.properties" /> 

但这(有趣)没有:

<context:property-placeholder location="#{ systemProperties['foo'] }" /> 

java.io.FileNotFoundException: Could not open ServletContext resource [/#{ systemProperties['foo'] }] 

你不会能够使用财产占位符${..}与th e PropertyPlaceholderConfigurer的定义。这是鸡蛋前面的鸡。

你总是可以继承PropertyPlaceholderConfigurer,并让它做你想做的(例如,呼叫setLocations()@PostConstruct方法之后,而不是使用<context:property-placeholder>,用途:

<bean class="com.foo.MyPropertyPlaceholderConfigurer"/> 
+0

我认为表达式语言允许这样做,正如[本文中关于用spring管理属性文件](http://www.summa -tech.com/blog/2009/04/20/6-tips-for-managing-property-files-with-spring/)。我将尝试了解需要在PropertyPlaceholderConfigurer中进行子类化的内容,以便能够弄清楚如何动态加载属性文件。这似乎是一个很简单的想法,现在看起来如此令人费解,现在与春天。 –