Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added a new method for loading properties from WebApp by Maz

...

How do I load a properties file?

Here are the two three most popular ways::

  • Use a classloader's getResource to get an url to the properties file and load it into the Properties. The properties file must be located within the webapp classpath (i.e. either WEB-INF/classes/... or in a jar.

A challenge is to get the classloader when you are in a static initializer:

No Format

  public class Config {
     private static java.util.Properties prop = new java.util.Properties();
     private static loadProperties() {
          // get class loader
          ClassLoader loader = Config.class.getClassLoader();
          if(loader==null)
	    loader = ClassLoader.getSystemClassLoader();

          // assuming you want to load application.properties located in WEB-INF/classes/conf/
          String propFile = "conf/application.properties";
          java.net.URL url = loader.getResource(propFile);
	  try{prop.load(url.openStream());}catch(Exception e){Syste,.err.println("Could not load configuration file: " + propFile);}
     }
  }

This method even works in a standalone java application. So it is my preferred way.

  • Use a ResourceBundle. See the Java docs for the specifics of how the ResourceBundle class works. Using this method, the properties file must go into the WEB-INF/classes directory or in a jar file contained in the WEB-INF/lib directory.
  • Another way is to use the method getResourceAsStream() from the ServletContext class. This allows you update the file without having to reload the webapp as required by the first method. Here is an example code snippet, without any error trapping:

...