Core Java
Imal Perera  

Using Property Files in EE Web Applications

Spread the love

Why we should use property files in java EE web applications specially ?

Currently Most popular web development language is Php, it is simple but powerful interpreted scripting language. Because php is not a compiled and interpreted language we can reach to the source code at any time and change it, then the site will soon start behave according to the change. This makes developer’s life easy since most often they have to change Parameters like Database name, Database password, Url etc after a successful upload to a host, but the problem of Java is it is an compiled and interpreted language so after building the site if you need to do a simple code change you will have to edit the source code build it and upload again to the server.

Because of the above reason it is not a good practice to use configuration parameters like Database details in a separate class file, instead we use a file which has .properties extension, variables of this file can be extracted in the run time with a little support from java.util.Properties class.

Below is an simple example of using a property file 

 

i will be first creating a class called MapProperty to in my com.utils.propertyexample  package. you can have it in any package you want and any name you like,

purpose of this class to wrap the property file.

now we need a property file. create a file called myapp.properties in the same package as the MapProperty.java  class

 

NOTE  :-  in a  .properties  file “#”  can be used to comment and we do not use semicolon “;” to indicate end , check the blow example

 

#this file contains the settings for the website..... 

#Database Password
DB_PASSWORD = 123

 

package com.utils.propertyexample;

import java.io.InputStream;
import java.util.Properties;

public class MapProperty {

	private static String DB_PASSWORD;
	private static Properties prop = null;

	public static void init() {
		try {
			if (prop == null) {
				// creating a Properties object and loading the myapp.properties
				prop = new Properties();
				InputStream propetystr = new MapProperty().getClass().getResourceAsStream("myapp.properties");
				prop.load(propetystr);

				// setting values read from myapp.properties
				DB_PASSWORD = prop.getProperty("DB_PASSWORD");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static String getDB_PASSWORD() {
		init();
		return DB_PASSWORD;
	}

}

Leave A Comment