title: Constants and properties in java
body: <p>Java best practices recommends read properties as constants. So, what do you think is the best approach to reach it? My approach is: A Configuration class to read the properties file only one time (singleton pattern) and use this class to read properties when needed as constants. And a Constants class to store:</p>
  
  <ul>
  <li>The properties name to find them in the properties file (eg app.database.url).</li>
  <li>Static constants (those that I don't want the user to config eg
  CONSTANT_URL="myurl.com").</li>
  </ul>
  
  <pre class="lang-java prettyprint-override"><code>public final class Configurations {
  
  private Properties properties = null;
  private static Configurations instance = null;
  
  /** Private constructor */
  private Configurations (){
      this.properties = new Properties();
      try{
          properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(Constants.PATH_CONFFILE));
      }catch(Exception ex){
          ex.printStackTrace();
      }
  }   
  
  /** Creates the instance is synchronized to avoid multithreads problems */
  private synchronized static void createInstance () {
      if (instance == null) { 
          instance = new Configurations ();
      }
  }
  
  /** Get the properties instance. Uses singleton pattern */
  public static Configurations getInstance(){
      // Uses singleton pattern to guarantee the creation of only one instance
      if(instance == null) {
          createInstance();
      }
      return instance;
  }
  
  /** Get a property of the property file */
  public String getProperty(String key){
      String result = null;
      if(key !=null &amp;&amp; !key.trim().isEmpty()){
          result = this.properties.getProperty(key);
      }
      return result;
  }
  
  /** Override the clone method to ensure the "unique instance" requeriment of this class */
  public Object clone() throws CloneNotSupportedException {
      throw new CloneNotSupportedException();
  }}
  </code></pre>
  
  <p>The Constant class contains the references to the properties and the Constants.</p>
  
  <pre><code>public class Constants {
  // Properties (user configurable)
  public static final String DB_URL = "db.url";
  public static final String DB_DRIVER = "db.driver";
  
  // Constants (not user configurable)
  public static final String PATH_CONFFILE = "config/config.properties";
  public static final int MYCONSTANT_ONE = 1;
  }
  </code></pre>
  
  <p>And the properties files would be:</p>
  
  <pre><code>db.url=www.myurl.com
  db.driver=mysql
  </code></pre>
  
  <p>To read the properties and constants would be:</p>
  
  <pre><code>// Constants
  int i = Constants.MYCONSTANT_ONE;
  // Properties
  String url = Configurations.getInstance().getProperty(Constants.DB_URL);
  </code></pre>
  
  <p>Do you think this is a good approach? What is your way to read properties and constants in Java?</p>
  
  <p>Thanks in advance.</p>