【问题标题】:How to load a configuration file at startup within tomcat如何在tomcat中启动时加载配置文件
【发布时间】:2011-02-13 04:54:12
【问题描述】:

我希望能够在启动 tomcat(apache commons 配置库)时为 webapp 加载我的配置,这是一种可能的方式:

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>

然后在 webapp 中通过

访问它们
this.cfg = (XMLConfiguration) servletRequest.getAttribute("mycfg");

【问题讨论】:

    标签: configuration tomcat web-applications startup


    【解决方案1】:

    没有。您将无法通过这种方式获得配置。您在 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");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-09
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 2021-09-04
      • 2019-12-30
      相关资源
      最近更新 更多