Ascalonian
Ascalonian

Reputation: 15193

Is there a way to use place holders in Apache PropertiesConfiguration

I have the following configuration setup using Apache Configuration:

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

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

I want to know if there is some way to use place holders in the properties file? For example, I want to have this:

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

And be able to pass in the value for the {0} place holder. Typically, you can usually do something like config.getString("some.message", String[] of values) but don't see anything like that.

Upvotes: 4

Views: 867

Answers (2)

Solorad
Solorad

Reputation: 914

As far as I know, Configuration class doesn't provide any formatters. So, for your task

  1. You can use MessageFormat as it was suggested by Bilguun. Please note, that format method is static.

  2. You can use String.format function.

Examples is bellow:

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

Upvotes: 1

Bilguun
Bilguun

Reputation: 130

I believe you could get property value with placeholder from a property file and then use MessageFormat to formatting the message to what you desired. Let's say you got following property in your property file:

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

So that you get and format this property like:

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));

Also, if you could use system variables or environmental variables if it is not changed on the fly

Upvotes: 1

Related Questions