Reading properties in EJB

One of the most compelling needs of applications is to read initialization properties. If your application is EJB-centric, then a very simple strategy is to read the properties from a File and store them in an EJB Singleton. Here is how to do it.

At first here is how our application looks like:

   |-------- WEB-INF
                |---- classes
                         |----- com
                                 |------ sample
                                           |------- EJBSingleton.class

As you can see, we have our EJB packaged as part of a Web application and we have stored our property file in the WEB-INF/classes folder so that it’s visible from the Web application classloader.

With Singleton EJBs is fairly simple to store properties in a variable class so that it can be retrieved via get/set by other classes using the EJB:


public class EJBSingleton {

       Properties properties;

	public void init() {
	   InputStream inputStream = this.getClass().getClassLoader()

	   properties = new Properties();
	   System.out.println("InputStream is: " + inputStream);
	   // Loading the properties

	   // Printing the properties
	   System.out.println("Read Properties."+properties);


Now you can read your properties across the application by simply injecting the EJB as follows:

EJBSingleton ejb;

Or, if your are using CDI:

EJBSingleton ejb;