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:

DemoApp.war
   |
   |-------- console.properties
   |
   |-------- 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:

@Singleton
@Startup

public class EJBSingleton {

       Properties properties;

	@PostConstruct
	public void init() {
	   InputStream inputStream = this.getClass().getClassLoader()
	  .getResourceAsStream("console.properties");

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

	   // 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:

@EJB 
EJBSingleton ejb;

Or, if your are using CDI:

@Inject
EJBSingleton ejb;
Found the article helpful? if so please follow us on Socials