我想用在属性中定义的密钥文件为这样的变量:属性文件:使用密钥变量
key1= value1
key2= value2
key3= key1
我尝试:
key3= {key1}
或
key3= ${key1}
但它没有工作!
有什么想法吗?
我想用在属性中定义的密钥文件为这样的变量:属性文件:使用密钥变量
key1= value1
key2= value2
key3= key1
我尝试:
key3= {key1}
或
key3= ${key1}
但它没有工作!
有什么想法吗?
Java的内置Properties类不会做你正在寻找的东西。
但有第三方库在那里做。 Commons Configuration是我用过的一个成功的例子。 PropertiesConfiguration
类完全符合你的要求。
所以,你可能有一个名为my.properties
文件看起来像这样:使用此文件可能看起来像这样
key1=value1
key2=Something and ${key1}
代码:
CompositeConfiguration config = new CompositeConfiguration();
config.addConfiguration(new SystemConfiguration());
config.addConfiguration(new PropertiesConfiguration("my.properties"));
String myValue = config.getString("key2");
myValue
将"Something and value1"
。
当您在属性文件中定义键的值时,它将被解析为文字值。所以当你定义key3= ${key1}
时,key3的值就是“$ {key1}”。
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Properties.html#load(java.io.InputStream)
我与惩教署同意,普通配置文件可能不是你的选择。我更喜欢采用Apache Ant(http://ant.apache.org/),在那里你可以做这样的事情:
<property name="src.dir" value="src"/>
<property name="conf.dir" value="conf" />
再后来,当你想使用键“src.dir的”,只是把它是这样的:
<dirset dir="${src.dir}"/>
使用Apache Ant的另一个好处是您也可以将.properties文件加载到Ant构建文件中。只需像这样导入它:
<loadproperties srcFile="file.properties"/>
.xml甚至更好:使用最新的Maven。 你可以用maven做一些整洁的东西。在这种情况下,你可以作出的.properties与此行是文件:在Maven的POM
key1 = ${src1.dir}
key2 = ${src1.dir}/${filename}
key3 = ${project.basedir}
。xml文件(位于项目的根目录),你应该做这样的事情:
<resources>
<resource>
<filtering>true</filtering>
<directory>just-path-to-the-properties-file-without-it</directory>
<includes>
<include>file-name-to-be-filtered</include>
</includes>
</resource>
</resources>
...
<properties>
<src1.dir>/home/root</src1.dir>
<filename>some-file-name</filename>
</properties>
这样,你会键的值在编译时间发生改变,这意味着编译后,你将有你的属性里面这个值文件:
key1 = /home/root
key2 = /home/root/some-file-name
key3 = the-path-to-your-project
这一行编译当你在同一个目录的pom.xml文件: MVN全新安装-DskipTests