­

My Quotes


When U were born , you cried and the world rejoiced
Live U'r life in such a way that when you go
THE WORLD SHOULD CRY





Free users please don't remove our link. Get the code again.

Friday, December 28, 2012

Load Properties dynamically

Use Apache Commons Configuration and you can re-load property file dynamically.

Here is the complete code snippet for you


Java Code

import java.util.Arrays;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;

public class ApacheCommonsTest {

private static final String PROPERTIES_FILE_NAME = "C:\\sampleconfig\\reloadconfig.properties"; // you can use your own folder for this

/**
* @param args
*/
public static void main(String[] args) {
ApacheCommonsTest classObj = new ApacheCommonsTest();
try {
classObj.getBackground();
classObj.getPieColors();
} catch (ConfigurationException e) {
e.printStackTrace();
}
}

private PropertiesConfiguration getPropertyConfig()
throws ConfigurationException {
PropertiesConfiguration config = null;
config = new PropertiesConfiguration(PROPERTIES_FILE_NAME);
config.setReloadingStrategy(new FileChangedReloadingStrategy());
config.setAutoSave(true);
return config;
}

private void readProperties() throws ConfigurationException {
PropertiesConfiguration config = getPropertyConfig();
config.load(PROPERTIES_FILE_NAME);
}

private void getPieColors() throws ConfigurationException {
readProperties();
String[] piecolors = getPropertyConfig().getStringArray("colors.pie");
System.out.println("colors.pie=" + Arrays.toString(piecolors));
}

private void getBackground() throws ConfigurationException {
readProperties();
String bgcolor = getPropertyConfig().getString("colors.background");
System.out.println("bgcolor=" + bgcolor);
}
}

Sample Property file
C:\\sampleconfig\\reloadconfig.properties


colors.pie=#FF0000,#00FF00,#0000FF,#123456
colors.background=#c53478


Jar files to run this program

You can get all the jar files from findjar.com

  1. commons-configuration-1.9.jar
  2. commons-lang-2.2.jar
  3. commons-logging-1.1.1.jar
Now no more reloading with server re-start


No comments :