Java App Configuration — Properties Alternative
Download Apache Commons Configuration
Believe me it's awesome!!
Create you your XML configuration file and keep it in same package to make life simple:
<?xml version="1.0" encoding="UTF-8"?> <!-- data.xml --> <config> <local> <url>http://localhost:8080</url> </local>
<dev> <url>http://example.com</url> </dev> </config>
Notice I'm configuring both local and dev environment is same file, cool!
And load it:
try { config = new XMLConfiguration(SolrConfig.class.getResource("data.xml")); EnvironmentConfiguration config = new EnvironmentConfiguration(); env = config.getString("env"); // Environment if (env==null) { env = "local"; // by default it's local } logger.info("'"+env+"' Environment detected!"); } catch (Exception e) { logger.severe("Configuration error: "+e.getMessage()); }
Note: you can access environment variables too and differentiate between various environments.
add a environment aware method to your code:
public String getProperty(String key) { key = env.trim()+"."+key.trim(); return this.config.getString(key); }
And that's how you access the property within your xml configuration: config.getProperty("url")
Have Fun.

















