Configuration 如何在tomcat中启动时加载配置文件
我希望能够在tomcat(apache commons配置库)启动时加载我的webapp配置,这是一种可行的方式:Configuration 如何在tomcat中启动时加载配置文件,configuration,tomcat,web-applications,startup,Configuration,Tomcat,Web Applications,Startup,我希望能够在tomcat(apache commons配置库)启动时加载我的webapp配置,这是一种可行的方式: public class MyAppCfg implements javax.servlet.ServletContextListener { private ServletContext context = null; @Override public void contextInitialized(ServletContextEvent event) { try{
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>
不,您无法通过这种方式获得配置。您正在servlet上下文中设置它,但在请求上下文中检索它 您需要像这样在Servlet init中检索cfg
public void init(final ServletConfig config) {
// log it to the ServletContext
ServletContext context = config.getServletContext();
this.cfg = (Configuration)context.getAttribute("mycfg");
}
public void init(final ServletConfig config) {
// log it to the ServletContext
ServletContext context = config.getServletContext();
this.cfg = (Configuration)context.getAttribute("mycfg");
}