1

Having a Java web application, how does one read properties file only once when the app is deployed (storing them later in some singleton)? Meaning, configuration changes would require redeployment.

Otherwise, is there an alternative way to prevent an app from constantly reading .properties file? Previously I had settings in my web.xml file, but now .properties is required.

Code used to read app settings from JBoss configuration path:

File f = new File(System.getProperty("jboss.server.config.dir"), 
                  "myappsettings.properties");
Properties p = new Properties();
p.load(new FileInputStream(f));
try {
   db_name = p.getProperty("DATABASE_NAME"));
   file_path = p.getProperty("FILE_PATH"));
   ...
} catch (Exception e) {
   ...
}
yosh
  • 3,245
  • 7
  • 55
  • 84
  • possible duplicate of [Java EE Enterprise Application: perform some action on deploy/startup](http://stackoverflow.com/questions/6120831/java-ee-enterprise-application-perform-some-action-on-deploy-startup) – jmj Aug 14 '12 at 08:21
  • @JigarJoshi I did not find that question when looking for my startup properties reading issue. – yosh Aug 14 '12 at 08:29
  • Most Java container class-loaders, cache what they read from classpath. I mean if you change the properties file which is stored in your classpath (in `/WEB-INF/classes` folder), the changes are not seen in the application till re-deployment, even if you execute the above code multiple times. – Amir Pashazadeh Aug 14 '12 at 08:42

2 Answers2

4

Starting with JEE6, another alternative to the ServletContextListener could be using a singleton startup bean:

@Singleton
@Startup    
public class PropertyRegistry {

  @PostConstruct
  private void init(){
    //do something
  }
}
ftr
  • 2,105
  • 16
  • 29
3

Implement your own ServletContextListener:

public class PropertiesReadingListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent event) {
        //read properties here...
        event.
          getServletContext().
          setAttribute("db_name", p.getProperty("DATABASE_NAME"));
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
    }
}

You must reference this class in web.xml:

<listener>
    <listener-class>com.example.PropertiesReadingListener</listener-class>
</listener>
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • 1
    @JigarJoshi: true, but I also added a tip how to place properties in servlet context as opposed to "*in some singleton*", so I'll keep it just in case ;-). – Tomasz Nurkiewicz Aug 14 '12 at 08:27
  • 1
    And that's a useful tip, I thought I needed singleton. Dziekuje ;) – yosh Aug 14 '12 at 08:37