Skip to content

Java: Loading properties from external file

January 18, 2013

Java (programming language)

It is common situation when you need to configure your application in different ways (e.g. default properties, CLI properties or getting them from external file).  Here is an example how to resolve problem you faced to using singleton pattern. External file properties is more prioritized over default ones. 

public class Settings {

public static final String EXTERNAL_PROPERTIES = "external.jbehave.properties";

private static final String PROPERTIES_FILE = "/jbehave.properties";

private static final String ROOT = Settings.class.getPackage().getName();

private static final String REMOTE_HOST_ADDRESS_PATH = ROOT + ".remoteHostAddress";

private static Settings instance;

static {
instance = loadInstance();
}

private String remoteHostAddress;

private Settings(Properties properties) {

jobsExecutionMode = getProperty(properties, JOBS_EXECUTION_MODE_PATH);
storyTimeoutInSec = toInt(getProperty(properties, STORY_TIMEOUT_IN_SEC_PATH), 1200);

remoteHostAddress = getProperty(properties, REMOTE_HOST_ADDRESS_PATH);
}

private static Settings getInstance() {

return instance;
}

private static Settings loadInstance() {

Properties properties = new Properties();
InputStream stream = Settings.class.getResourceAsStream(PROPERTIES_FILE);

try {

properties.load(stream);

} catch (IOException e) {

throw new RuntimeException(e);
}

if (System.getProperty(EXTERNAL_PROPERTIES) != null) {

try {

InputStream externalStream = new FileInputStream(
new File(System.getProperty(EXTERNAL_PROPERTIES)));

Properties externalProperties = new Properties();
externalProperties.load(externalStream);
properties.putAll(externalProperties);  // merging external properties with default ones

} catch (Exception e) {

LOGGER.info(e.toString());
}
}

return new Settings(properties);
}

private static String getProperty(Properties properties, String key) {

String value = properties.getProperty(key);

if (value == null) {
throw new RuntimeException("The property '" + key + "' is not specified.");
}

return value;
}

public static String getRemoteHostAddress() {
return getInstance().remoteHostAddress;
}
}

Advertisements

From → Automation, Java

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: