【问题标题】:Loading spring XML from location different from classpath从与类路径不同的位置加载 spring XML
【发布时间】:2013-11-12 22:46:29
【问题描述】:

我正在尝试使用 ClassPathXmlApplicationContext 类读取 spring xml,如下所示。

    ApplicationContext context = new ClassPathXmlApplicationContext("file:../WebContent/WEB-INF/dispatcher-servlet.xml");
    Service service = (Service ) context.getBean("service");

但我收到 FileNotFound 异常。 dispatcher-servlet.xml 位于 WebContent/WEB-INF/dispatcher-servlet.xml 下。如果我将文件移动到 Src 文件夹,它工作正常。

我尝试了不同的方法,例如

    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:../WebContent/WEB-INF/dispatcher-servlet.xml");

 ApplicationContext context = new ClassPathXmlApplicationContext("/WEB-INF/dispatcher-servlet.xml");

但是这些不起作用。有人可以提供一些输入。

【问题讨论】:

    标签: java spring jakarta-ee


    【解决方案1】:

    来自Spring documentation

    ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml");
    

    【讨论】:

    • 如何给出相对路径?下面的路径不起作用classpath:../WebContent/WEB-INF/dispatcher-servlet.xml
    • AFAIK,类路径没有 .. 目录。将类路径视为一种虚拟/(根)文件系统。如果您需要您的地址是相对的,那么您可能需要使用 FileSystemXmlApplicationContext。
    【解决方案2】:

    在你的 web.xml 中试试这个:

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    

    如果您需要在代码中执行此操作,请使用 ServletContextResource。见here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多