如何在文件系统上使用property-placeholder文件

bla*_*nda 16 java spring

我们曾经有办法从类路径上的文件加载属性:

<context:property-placeholder location="classpath:myConfigFile.properties" />
Run Code Online (Sandbox Code Playgroud)

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

在Java中:

  System.setProperty("my.prop.file", "/path/to/myConfigFile.properties");
Run Code Online (Sandbox Code Playgroud)

在Spring XML中:

<context:property-placeholder location="${my.prop.file}" />
Run Code Online (Sandbox Code Playgroud)

我也是这样尝试过的,感谢Luciano的一个想法:

<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>
Run Code Online (Sandbox Code Playgroud)

我尝试过的一切都失败了.无论我将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)
Run Code Online (Sandbox Code Playgroud)

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

事实证明,运行Java程序的脚本存在加载spring文件的问题.谢谢你的帮忙.我将要求删除此问题,因为原始代码毕竟有效.谢谢您的帮助.

sou*_*ica 15

这对我有用:

<context:property-placeholder location="file:/path/to/myConfigFile.properties" />
Run Code Online (Sandbox Code Playgroud)

但是(有趣的是)没有:

<context:property-placeholder location="#{ systemProperties['foo'] }" />
Run Code Online (Sandbox Code Playgroud)

我有

java.io.FileNotFoundException: Could not open ServletContext resource [/#{ systemProperties['foo'] }]
Run Code Online (Sandbox Code Playgroud)

您无法使用${..}PropertyPlaceholderConfigurer定义的属性占位符.这是鸡蛋前的鸡肉.

你总是可以继承PropertyPlaceholderConfigurer并让它做你想做的任何事情(例如,setLocations()@PostConstruct方法中调用.然后,而不是使用<context:property-placeholder>,使用:

<bean class="com.foo.MyPropertyPlaceholderConfigurer"/>
Run Code Online (Sandbox Code Playgroud)


Luc*_*ano 6

这个怎么样?

<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>
Run Code Online (Sandbox Code Playgroud)