How to load a configuration file at startup within tomcat

Posted by Alex on Stack Overflow See other posts from Stack Overflow or by Alex
Published on 2010-04-28T06:04:28Z Indexed on 2010/05/01 13:37 UTC
Read the original article Hit count: 269

Filed under:
|
|
|

I want to be able to load my configuration for the webapp at startup of tomcat (apache commons configuration library) is this a possible way:

public class MyAppCfg implements javax.servlet.ServletContextListener {

private ServletContext context = null;

@Override
public void contextInitialized(ServletContextEvent event) {
    try{
        this.context = event.getServletContext();

        XMLConfiguration config = new XMLConfiguration("cfg.xml");
        config.setReloadingStrategy(new FileChangedReloadingStrategy());

        this.context.setAttribute("mycfg", config);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void contextDestroyed(ServletContextEvent arg0) {
    this.context = null;
   }
}

web.xml

<listener>
    <listener-class>mypackage.MyAppCfg</listener-class>    
</listener>

and later acces them in the webapp via

this.cfg = (XMLConfiguration) servletRequest.getAttribute("mycfg");

© Stack Overflow or respective owner

Related posts about configuration

Related posts about webapp