How to load a configuration file at startup within tomcat
- by Alex
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");