如何在文件系统上对文件使用属性占位符

2022-09-02 21:31:20

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

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

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

在爪哇:

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

在春季XML:

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

我也尝试过这种方式,这要归功于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>

我尝试过的所有方法都失败了。无论我将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。

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


答案 1

这对我确实有效:

<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'] }]

您将无法使用具有属性占位符配置器定义的属性占位符。这是先鸡先于蛋。${..}

您始终可以子类 PropertyPlaceholderConfigurer 并让它执行任何您想要的操作(例如,在方法中调用)。然后,不要使用 ,请使用:setLocations()@PostConstruct<context:property-placeholder>

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

答案 2

这种方式呢?

<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>

推荐