3

我正在尝试使用属性占位符来加载一些属性文件,并且我想使用系统属性指定其中一个文件的名称,以便我可以根据我的应用程序运行的环境加载不同的文件。

最初我尝试了以下方法:

<context:property-placeholder location="classpath:environment_common.properties,classpath:environment_${app_env}.properties" />

我验证了系统属性(app_env)设置正确(例如,“bar”),但 Spring 正在加载错误的文件(例如,environment_foo.properties)。

接下来我尝试使用SpEL:

<context:property-placeholder
        location="#{ 'classpath:environment_common.properties,classpath:environment_'.concat(systemProperties['app_env'] }.properties) }" />

但似乎context:property-placeholder不支持SpEL:

java.io.FileNotFoundException: Could not open ServletContext resource [/#{'classpath:environment_common.properties]

它看起来好像context:property-placeholder有自己的解析器来寻找逗号来分隔多个属性文件,但它不是首先将值传递给 SpEL 来评估它。

我应该如何使用context:property-placeholder,还是应该绕过它PropertyPlaceHolderConfigurer直接使用?

4

2 回答 2

1

我今天遇到了这个问题。这是我的解决方案:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" 
        value="classpath:#{(T(java.lang.System).getProperty('my.property', 'development.properties'))}"/>
</bean> 

我没有使用预定义的变量 systemProperties,但假设您可以根据需要使用。

于 2012-08-01T20:51:41.190 回答
1

我从未尝试在属性占位符元素中直接使用 SpEL。不过,似乎有一个错误提交给它。作为一个相当简单的解决方法:

<context:property-placeholder properties-ref="props" />
<util:properties id="props" location="#{ your expression here }"/>
于 2011-08-05T04:39:53.430 回答