Rails-like configuration of different environments in JAVA – YAML instead of properties file
April 21st, 2010 | By Christoph in Software-Development | No Comments »This article shows a simple code example how you can replace a standard JAVA properties file (.ini) with a more flexible .yml (YAML) file using the JYAML library.
I used this to store configuration parameters for an application for different environments (e.g. development vs. production) in one central file. This is how the RubyOnRails guys are doing this e.g. in the database.yml.
1. See how the usual standard config files look like.
# config.ini file # Database dbconnectionurl=jdbc:mysql://localhost:3306/mydb dbuser=dbuser dbpass=dbpasswd
As you see it just has key/value pairs. There is also no notion of an “environement” which means I could use a separate file to store information for different environments. But I want everything centralized.
And here the new yaml file:
# config.yml
development:
# Database
dbconnectionurl: jdbc:mysql://localhost:3306/mydevelopmentdb
dbuser: dbuserdevelopment
dbpass: dbpasswddevelopment
production:
# Database
dbconnectionurl: jdbc:mysql://localhost:3306/myproductiondb
dbuser: dbuserproduction
dbpass: dbpasswdproduction
As you can see the config.yml contains two sections. The first section is the configuration for the development environment, which is the default per my convention. The second section contains the configuration for the production environment.
2. Now here is the JAVA code which first loads the config.ini file using the standard approach and second loads the config.yml using the JYAML library and puts them into properties as well. Using that approach we almost don’t have to change any application code, because our application still uses a Java Properties object.
public static void main(String[] args) { /*** * 1. Load Properties using traditional approach * from config.ini */ try { Properties props = new Properties(); props.load(new FileReader(new File("config.ini"))); System.out.println(props.toString()); } catch (FileNotFoundException e) { } catch (IOException e) { } /*** * 2. Try to do the same based on */ try { Properties props = new Properties(); HashMap yamlConfig = (HashMap) Yaml.load(new File("config.yml")); // now check which environment to load (production or development) // development is default String environment = System.getProperty("MYENVIRONMENT","development"); HashMap propertiesFromYamlForEnvironment = yamlConfig.get(environment); props.putAll(propertiesFromYamlForEnvironment); System.out.println(props.toString()); } catch (FileNotFoundException e) { } catch (IOException e) { } }
As you can see the line
String environment = System.getProperty("MYENVIRONMENT","development");
is responsible to read the environment from a system property. you can set this by setting the usual -DMYENVIRONMENT=”production” when you start you java program.
That’s it. Pretty simple but powerful.
You can read more about JYAML in their tutorial.