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;
Recommended Articles
Configure MDB Properties Dynamically with JBoss EAP and WildFly via System Properties
Learn how to dynamically configure MDB properties using system properties in JBoss EAP and WildFly, enabling a flexible and effective configuration for your message-driven beans.
Exposing an Enterprise Java Bean as a Singleton: A Simple Approach
Learn how to use the @Singleton annotation to expose an Enterprise Java Bean as a single instance, ensuring thread-safe and efficient management of your application's resources.
Call an EJB from another application in WildFly using EJB Lookup
Learn how to invoke EJBs from a remote EJB Client using WildFly's EJB lookup feature. This tutorial covers the steps for creating an EJB server project, setting up security, and configuring dependencies.
EJB 3.1: Five Major Innovations and Simplified Development
Discover five key improvements in EJB 3.1, including the elimination of mandatory interfaces for Session Beans and the introduction of Singleton EJBs. #WildFly #JavaEE #Middleware #CloudNative