Reading properties in EJB

User Rating: 2 / 5

Star ActiveStar ActiveStar InactiveStar InactiveStar Inactive
 

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;

Thanks to Jaikiran Pai for sharing the original idea of this solution.

Related articles available on mastertheboss.com

EJB 3.0 tutorial : Session Beans

Enterprise JavaBeans (EJB) technology is a J2EE technology for de

JBoss MDB 3.0

Message-driven beans (MDBs) are stateless, server-side, transacti

JBoss EJB 3 BMT

In a Bean Managed Transaction, the code in the session or message

How do you keep your EJB callbacks separated from biz. methods?

JBoss daily recipe

How to set EJB timeout period ?

JBoss recipe of the day

How to add a Selector with MDB 3.0 ?

Message selectors allow an MDB to be more selective about the mes

Follow us on Twitter