Java 使用相对于配置文件的路径引用 Spring 属性文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3611250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reference Spring properties file using path relative to config file
提问by stevec
I am moving properties from inside my Spring config file to a separate properties file. This is included in the config file with
我正在将 Spring 配置文件中的属性移动到单独的属性文件中。这包含在配置文件中
<bean class="org.springframework.beans.factory.config.PropertyPlaceHolderConfigurer">
<property name="location" value="file:properties/${CONFIG_MODE}/service.properties" />
</bean>
As it stands, the location of the properties file is relative to the current working directoryof the server process.
就目前而言,属性文件的位置相对于服务器进程的当前工作目录。
This creates the requirement that the process must be started from a specific working directory, and even worse allows for the (admittedly remote) possibility that it could pick up an entirely different properties file - for example if it was started with the working directory set to an older version of the service.
这产生了必须从特定工作目录启动进程的要求,更糟糕的是允许(公认的远程)它可以选择完全不同的属性文件的可能性 - 例如,如果它在工作目录设置为旧版本的服务。
I'd like to reference the properties file using a path that is relative to the directory containing the config file.
我想使用相对于包含配置文件的目录的路径来引用属性文件。
Looking at FileSystemResource, it seems createRelativemight be what I need, but I can't figure out how to use it in the config file.
查看FileSystemResource,似乎createRelative可能是我需要的,但我不知道如何在配置文件中使用它。
Thanks,
谢谢,
Steve
史蒂夫
采纳答案by skaffman
I don't know of a way to do that.
我不知道有什么方法可以做到这一点。
What you can do, however, is load the properties file from the classpath:
但是,您可以做的是从类路径加载属性文件:
<bean class="org.springframework.beans.factory.config.PropertyPlaceHolderConfigurer">
<property name="location" value="classpath:path/to/service.properties" />
</bean>
The classpath location of your properties file is a far more predictable situation, and it'll work as long as your classpath is set up properly.
您的属性文件的类路径位置是一个更可预测的情况,只要您的类路径设置正确,它就会工作。
回答by Craig Swing
Using 3.1, you can keep the files off of the classpath if you want.
使用 3.1,您可以根据需要将文件保留在类路径之外。
With the following bean definition,
使用以下 bean 定义,
<bean class=
"org.springframework.beans.factory.config.PropertyPlaceHolderConfigurer">
<property name="location"
value="file:${props.path}/service.properties" />
</bean>
you can set a property using the java command line
您可以使用 java 命令行设置属性
java ... -Dprops.path=path/to/where/it/is
回答by A-Coder
Supposing you have placed the config.properties file inside WEB-INF Then:
假设您已将 config.properties 文件放在 WEB-INF 中,然后:
<bean id="propertyConfigurerInternal"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:../config.properties</value>
</property>