属性文件:使用密钥作为变量

IT小君   2021-12-09T03:32:48

我想使用在属性文件中定义的键作为这样的变量:

key1= value1
key2= value2
key3= key1

我尝试:

key3= {key1}

或者

key3= ${key1}

但它不起作用!

有什么想法吗?

点击广告,支持我们为你提供更好的服务
评论(3)
IT小君

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"

2021-12-09T03:32:48   回复
IT小君

当您在属性文件中定义键的值时,它将被解析为文字值。因此,当您定义时key3= ${key1},key3 的值为“${key1}”。

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Properties.html#load(java.io.InputStream )

我同意csd,普通的配置文件可能不是你的选择。我更喜欢使用 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"/>
2021-12-09T03:32:48   回复
IT小君

.xml 更好:使用最新的 Maven。你可以用 maven 做一些巧妙的事情。在这种情况下,您可以创建一个包含以下行的 .properties 文件:

key1 = ${src1.dir}
key2 = ${src1.dir}/${filename}
key3 = ${project.basedir}

在 maven 的 pom.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 clean install -DskipTests

2021-12-09T03:32:48   回复