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

4

我使用Apache Configuration 进行如下配置:

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)的方式来实现,但是我没有看到类似的方法。

2个回答

1

我相信你可以从属性文件中使用占位符获取属性值,然后使用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));

此外,如果您能使用系统变量或环境变量而不是实时更改,则更好。

1
据我所知,Configuration类没有提供任何格式化程序。因此,对于您的任务,
  1. 您可以像Bilguun建议的那样使用MessageFormat。请注意,format方法是静态的。
  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}!

Example 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"));
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接