walters
walters

Reputation: 1467

How to reference a system property within a user-defined .properties file?

I want to define a property for a working directory(say work.dir=/home/username/working-directory), for my production .properties file, without hard-coding the /home/username.

I want to reference the system property user.home in place on the hard-coded /home/username, to make work.dir more generic.

How do I reference the system property and concatenate it will other user-defined strings in a user-defined .properties?

Note: I don't want to access the user.home property in my java code, but from the .properties that I have defined. I want to be able to replace the value of the work.dir with different value for both my production and development(JUnit tests for example).

Upvotes: 11

Views: 7449

Answers (3)

fglez
fglez

Reputation: 8552

You can manage your properties with Commons Configuration and use Variable Interpolation

If you are familiar with Ant or Maven, you have most certainly already encountered the variables (like ${token}) that are automatically expanded when the configuration file is loaded. Commons Configuration supports this feature as well[...]

That would allow a .properties file with

work.dir=${user.home}/working-directory

Upvotes: 5

Luigi
Luigi

Reputation: 8847

This feature is not available in java.util.Properties. But many libraries add variable substitution to properties.

Here an example of what you are trying to do using OWNER API library (see paragraph "importing properties"):

public interface SystemPropertiesExample extends Config {
    @DefaultValue("Welcome: ${user.name}")
    String welcomeString();

    @DefaultValue("${TMPDIR}/tempFile.tmp")
    File tempFile();
}

SystemPropertiesExample conf =
        ConfigFactory.create(SystemPropertiesExample.class, System.getProperties(), System.getenv());
String welcome = conf.welcomeString();
File temp = conf.tempFile();

Upvotes: 0

Andy Thomas
Andy Thomas

Reputation: 86509

Get the property from the file, then replace supported macros.

String propertyValue = System.getProperty("work.dir");
String userHome = System.getProperty("user.home" );
String evaluatedPropertyValue = propertyValue.replace("$user.home", userHome );

Upvotes: 4

Related Questions