1

我正在尝试将应用程序的配置文件与其战争分开。我想将所有属性文件保存在磁盘上的目录中。然后,战争中唯一需要的属性就是配置目录的路径(假设它在一个名为 的文件中config.properties):

config.dir = /home/me/config

现在在 spring 配置中,我想加载这个文件(以便我知道其他文件在哪里),然后是外部文件:

<bean id="propertySourcesPlaceholderConfigurer"
 class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:META-INF/config.properties</value>
            <value>${config.dir}/other.properties</value>
        </list>
    </property>
</bean>

但这不起作用,占位符未解决:

java.io.FileNotFoundException: class path resource [${config.dir}/config.properties] cannot be opened because it does not exist

我还尝试使用单独的 bean 类型PropertySourcesPlaceholderConfigurer- 它没有多大帮助。

你知道我怎么能做到这一点吗?

4

2 回答 2

3

The problem is that the configurer bean has to be fully constructed before it can resolve placeholders in the other bean definitions in the context, so you can't use a placeholder expression in the definition of the configurer that would need to be resolved by the configurer itself.

You could instead put the path to your config dir into web.xml as a context-param

<context-param>
  <param-name>configDir</param-name>
  <param-value>/home/me/config</param-value>
</context-param>

and then access it as #{contextParameters.configDir} in your Spring config

<bean id="propertySourcesPlaceholderConfigurer"
 class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>#{contextParameters.configDir}/other.properties</value>
        </list>
    </property>
</bean>

Or you may be able to do it with two separate configurer beans with different values of placeholderPrefix, one loading the config.properties and then filling in the @{config.dir} placeholder in the other, which then loads the external config file.

于 2013-03-30T19:27:49.810 回答
2

This can be resolved by registering a PropertySource for the default environment. One of the ways this can be done is using Java Configuration:

@Configuration
@PropertySource("classpath:META-INF/config.properties")
public class MyConfig {

}

With this in place the placeholder should get resolved:

<bean id="propertySourcesPlaceholderConfigurer"
 class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>${config.dir}/other.properties</value>
        </list>
    </property>
</bean>
于 2013-03-30T19:31:58.237 回答