有没有办法在 Apache PropertiesConfiguration 中使用占位符

Is there a way to use place holders in Apache PropertiesConfiguration

我使用 Apache 配置设置了以下配置:

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;

Configuration config = new PropertiesConfiguration("config.properties");

我想知道是否有一些方法可以在属性文件中使用占位符?例如,我想要这个:

some.message = You got a message: {0}

并且能够为 {0} 占位符传入值。通常,您通常可以执行类似 config.getString("some.message", String[] of values) 的操作,但看不到类似的内容。

我相信您可以从 属性 文件中获取带有占位符的 属性 值,然后使用 MessageFormat 将消息格式化为您想要的格式。假设您在 属性 文件中关注 属性:

some.message = "Hey {0}, you got message: {1}!"

这样你就可以得到并格式化这个 属性 就像:

message will be "Hey {0}, you got message: {1}!"    
String message = config.getString("some.message");

MessageFormat mf = new MessageFormat("");

//it will print: "Hey Thomas, you got message: 1"
System.out.println(mf.format(message, "Thomas", 1));

此外,如果您可以使用系统变量或环境变量,如果它不被即时更改的话

据我所知,配置 class 不提供任何格式化程序。所以,为了你的任务

  1. 您可以使用 Bilguun 建议的 MessageFormat。请 请注意,该格式方法是 static.

  2. 您可以使用String.format函数。

示例如下:

config.properties

enter some.message.printf=%1$s\, you've got a message from %2$s \n
some.message.point.numbers =Hey {0}\, you got message: {1}!

例子class

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

import java.text.MessageFormat;

public class ConfigurationTest {


    public static void main(String[] args) throws ConfigurationException {
        Configuration config = new PropertiesConfiguration("config.properties");

        String stringFormat = String.format(config.getString("some.message.printf"), "Thomas", "Andrew");
        // 1 String format
        System.out.println(stringFormat);
        // 2 Message Format
        System.out.println(MessageFormat.format(config.getString("some.message.point.numbers"), "Thomas", "Hello"));
    }
}