Luis Alves
Luis Alves

Reputation: 1286

EJB properties file

In my project I have 2 modules, a ejb and a war module. In the war module i have a properties file that is processed when I start the web application (by a listener). For each property in this properties file, i add it to the servlet context. So, my question is: is it possible to access this properties, in the servlet context, from a enterprise java bean in the ejb module? I want to do something like this, but in a ejb:

ServletContext sc = myservlet.getServletContext(); 
String xpto =  sc.getAttribute("my-attr");

If this is not possible, what is the alternative? Thanks!

P.S I'm using netbeans and glassfish.

Upvotes: 0

Views: 2555

Answers (2)

Alexander Rühl
Alexander Rühl

Reputation: 6959

Speaking of alternatives, it might be worth a thought to use configuration stored in database, at least if you already have a database connection in your application and have control over the database schema.

We use this technique in all our web applications, mainly for two reasons:

  1. Changes to a property can be done during runtime without monitoring file changes, they can be done by the application itself and one does not need to know a path outside of the deployed application.
  2. Properties can have additional information, such as a type (e.g. number, date, string), a default value, a comment or a user who changed it.

For implementing it, you'll create an application-scoped component which accesses the database properties for the rest of the application.

Upvotes: 1

ndnookala
ndnookala

Reputation: 131

ServletContext is always loaded ahead in the Servlet lifecycle loading. Ref to this link. As you see the Listeners are loaded after the ServletContext is loaded when application starts. You can have your code in the listener class that extends ServletContextListener. Ensure you are extending correct Listener as given in the link.

In your situation, One of the alternative is to have a Singleton class load all the properties from the properties file. for ex: ApplicationPropertiesLoader class can have a Properties map attribute to store the key value pairs of that property file. This class can have a getProperty method that always refer to its internal Properties.

In your servlet class refer to this singleton class to load the properties as required.

Upvotes: 1

Related Questions