Wednesday, October 26, 2011

Properties file

Use case: Use the same property file across deployment environments.

I like the idea of using the same war/ear being deployed/promoted through the deployment life-cycle.  I have seen projects, where the properties are stored in files like dev.properties test.properties and the build tool decides which property file to choose for each build.  This means a different build per environment.

To achieve this it is very simple using Apache Commons Configuration


My properties file looks like:

environment=${sys:env}
#Properties that do not vary per environment
a.general.property=propertyValue 

#Properties that vary
dev.a.property=value
test.a.property=value2
prod.a.property=value3


The java code is as follows:

        String fName = "C:\\Users\\config.properties";
       
        CompositeConfiguration
compositeConfig = new CompositeConfiguration();
       
        try
        {
            //Load the properties file
            PropertiesConfiguration pc = new PropertiesConfiguration(configFile);
            //Get the environment name, usually passed in as a -D parameter
            String prefix = pc.getString("environment");
            log.info("prefix is " +prefix);
            //Filter the configuration with the environment prefix
            Configuration envConfig =  pc.subset(prefix);
           
            log.trace(ToStringBuilder.reflectionToString(envConfig));
            //Add the filtered configuration to the composite
            compositeConfig.addConfiguration(envConfig);
            //Add the complete configuration to the composite, so that we have access to the non-environment specific properties
            compositeConfig.addConfiguration(pc);
        } catch (ConfigurationException e)
        {
            log.error("Error while reading properties.", e);
        }
Now to access a property, you will need to call compositeConfig.getProperty("a.property");  
This will return the right value depending on which environment that the application is running at.

Note:
  1. You will need to have an environment variable env set.  For development it will be set as -Denv="dev" and so on...
  2. The first property environment=${sys:env} will automagically be replaced by the PropertiesConfiguration class, no special processing is necessary.








No comments:

Post a Comment